220v
젝무의 개발새발
220v
전체 방문자
오늘
어제
  • 분류 전체보기 (255)
    • AI (35)
      • ML, DL 학습 (30)
      • 논문 리뷰 (4)
      • 실습 및 프로젝트 (1)
    • Algorithm (145)
      • LeetCode (13)
      • 프로그래머스 (35)
      • 백준 (96)
      • 알고리즘, 문법 정리 (1)
    • Mobile, Application (17)
      • Flutter (10)
      • iOS, MacOS (7)
    • BackEnd (7)
      • Flask (1)
      • Node.js (5)
      • Spring, JSP..etc (1)
    • Web - FrontEnd (18)
      • JavaScript, JQuery, HTML, C.. (12)
      • React (6)
    • DataBase (1)
      • MySQL (1)
      • Firebase Firestore (0)
      • Supabase (0)
    • Git (1)
    • 기타 툴 및 오류 해결 (3)
    • 강의 (5)
      • Database (3)
      • 암호학 (2)
      • 알고리즘 (0)
    • 후기와 회고 (2)
    • 블로그 꾸미기 (1)
    • 일상과 이것저것 (20)
      • 맛집 (12)
      • 세상사는일 (4)
      • 도서리뷰 (1)
      • 이런저런 생각들 (잡글) (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 백준
  • IMPLEMENT
  • 오블완
  • disjoint set
  • REACT
  • Greedy
  • top-down
  • Dynamic Programming
  • brute-Force
  • Minimum Spanning Tree
  • dfs
  • topological sort
  • 다익스트라
  • 프로그래머스
  • union-find
  • 구현
  • binary search
  • Lis
  • implementation
  • 티스토리챌린지
  • Mathematics
  • Priority Queue
  • Prefix Sum
  • dp
  • 위상 정렬
  • Backtracking
  • bitmasking
  • simulation
  • two pointer
  • BFS

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/LeetCode

[LeetCode/릿코드] 948. Bag of Tokens - Python

2024. 3. 4. 20:06

[Medium]

 

https://leetcode.com/problems/bag-of-tokens/

 

풀이

tokens 배열을 오름차순 정렬해준 후, Two Pointer 기법을 이용해 풀어주면 쉽게 풀이할 수 있다.

 

curl, curr 이라는 두 개의 커서를 각각 0, len(tokens) 로 초기화한 뒤, 차례로 진행해주면 된다.

현재 power가 왼쪽 커서(curl)의 토큰값보다 크다면 power를 낮추고 score를 올린 뒤(Face-up), 커서를 오른쪽으로 한 칸 이동.

현재 power가 왼쪽 커서(curl)의 토큰값보다 작다면, score가 1 이상이며, 왼쪽 커서와 오른쪽 커서가 같은 곳을 가리키지 않을 때, score를 낮추고 power를 올린다. (Face-down)

왼쪽 커서와 오른쪽 커서가 같은 곳을 가리킨다면, Face-down 이후 score를 올릴 token이 남지 않기 때문에, Face-down을 할 필요가 없다. (이미 오름차순 정렬을 했기 때문이다.)

두 if문 모두를 충족하지 않는다면, 게임을 할 필요가 없는 토큰들만 남은 것이므로, 게임을 종료한다.

 

AC.

def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
    tokens = list(sorted(tokens))
    score = 0

    curl = 0
    curr = len(tokens)-1

    while curl <= curr:
        if power >= tokens[curl]:
            power -= tokens[curl]
            score += 1
            curl += 1
        elif curl+1 < curr and score > 0:
            power += tokens[curr]
            score -= 1
            curr -= 1
        else:
            break

    return score

 

    'Algorithm/LeetCode' 카테고리의 다른 글
    • [LeetCode] 1696. Jump Game VI
    • [LeetCode] 97. Interleaving String
    • [LeetCode] 509. Fibonacci Number
    • [LeetCode/릿코드] 128. Longest Consecutive Sequence (220705 daily challenge)
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바