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)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

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

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/LeetCode

[LeetCode] 1696. Jump Game VI

2022. 7. 10. 03:45

접근1

DP.. Top-Down 방식으로 재귀를 이용해 구현.

i번째부터 점프를 시작할 때의 최대 score를 score[i] 라고 저장 (메모이제이션)

그렇게 score[0]을 구해가는 방법.

class Solution:
    def maxResult(self, nums: List[int], k: int) -> int:
        lenOfnum = len(nums)

        # index 'i' 부터 시작했을 때의 최대 score
        score = {lenOfnum-1: nums[lenOfnum-1]}

        # end index부터 반대로 순회


        def dp(i):
            a = score.get(i, None)
            if i + 1 == lenOfnum:
                return nums[lenOfnum-1]
            if a != None:
                return a

            tempScore = set()
            for j in range(1, k+1):
                if i+j < lenOfnum:
                    tempScore.add(dp(i+j))

            score[i] = max(tempScore) + nums[i]

            return score[i]
        
        return dp(0)

시간초과.

 

접근2

그렇다면... Bottom-Up 방식으로 풀어야 시간초과가 안 나는걸까?

Bottom-Up 방식의 for문으로 바꿔봄.

class Solution:
    def maxResult(self, nums: List[int], k: int) -> int:
        lenOfnum = len(nums)

        # index 'i' 부터 시작했을 때의 최대 score
        score = {lenOfnum-1: nums[lenOfnum-1]}

        # end index - 1 부터 반대로 순회
        for i in range(lenOfnum-2, -1, -1):
            tempScore = set()
            for j in range(1, k+1):
                if i+j < lenOfnum:
                    tempScore.add(score[i+j])

            score[i] = max(tempScore) + nums[i]

        return score[0]

근데도 시간초과.

 

접근3, 포기

그럼 뭔가 계산과정을 줄일 게 없나 생각해보자..

하고 짜다가.. 도저히 해결법이 안 나옴.

하고 discuss를 봤다..

deque(queue)를 써서 풀이하더라.

https://leetcode.com/problems/jump-game-vi/discuss/1261753/JS-Python-Java-C%2B%2B-or-Easy-DP-Deque-Solution-w-Explanation

class Solution:
    def maxResult(self, nums: List[int], k: int) -> int:
        n = len(nums)
        deq = deque([n-1])
        for i in range(n-2, -1, -1):
            if deq[0] - i > k: deq.popleft()
            nums[i] += nums[deq[0]]
            while len(deq) and nums[deq[-1]] <= nums[i]: deq.pop()
            deq.append(i)
        return nums[0]

Topic쪽 보니까, 우선순위 큐(힙) 이 있던데..

좀 더 공부해야겠음 ㅎㅎ;

    'Algorithm/LeetCode' 카테고리의 다른 글
    • [LeetCode/릿코드] 948. Bag of Tokens - Python
    • [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.

    티스토리툴바