[leetcode] 54, 55, 121, 122

shsh·2021년 8월 6일
0

leetcode

목록 보기
141/161

121. Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

My Answer 1: Accepted (Runtime: 1032 ms - 62.81% / Memory Usage: 25.1 MB - 82.45%)

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        ans = 0
        buy = max(prices)
        for i in range(len(prices)):
            if buy > prices[i]:
                buy = prices[i]
            ans = max(ans, prices[i] - buy)
        
        return ans

더 작은 값이 나오면 buy
buy 보다 큰 값들과의 차이를 ans 에 update

예전에 풀던 게 강력했는지 stock 문제는 익숙~


122. Best Time to Buy and Sell Stock II

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

My Answer 1: Accepted (Runtime: 60 ms - 73.34% / Memory Usage: 15 MB - 65.66%)

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        ans = 0
        buy = max(prices)
        for i in range(len(prices)):
            if buy < prices[i]:
                ans += prices[i] - buy
            buy = prices[i]
        
        return ans

이전 값 (buy) 보다 큰 값이 나오면 냅다 팔아버리기


54. Spiral Matrix

https://leetcode.com/problems/spiral-matrix/

My Answer 1: Accepted (Runtime: 28 ms - 84.00% / Memory Usage: 14 MB - 95.12%)

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        ans = []
        
        m = len(matrix)-1
        n = len(matrix[0])-1
        i, j = 0, 0
        
        while i <= m and j <= n:
            if i <= m:
                for k in range(j, n+1):
                    ans.append(matrix[i][k])
                i += 1
            if j <= n:
                for k in range(i, m+1):
                    ans.append(matrix[k][n])
                n -= 1
            if i <= m:
                for k in range(n, j-1, -1):
                    ans.append(matrix[m][k])
                m -= 1
            if j <= n:
                for k in range(m, i-1, -1):
                    ans.append(matrix[k][j])
                j += 1
        
        return ans

문제 고대로..

오른쪽 -> 아래 -> 왼쪽 -> 위 순서대로 ans 에 append
각 방향마다 범위 체크 한번 더 해줘야 중복되지 않는다...!!!

오른쪽) [i][j ~ n] 까지의 값 & i 번째 row 는 다 본거니까 i += 1
아래) [i ~ m][n] 까지의 값 & n 번째 column 은 다 본거니까 n -= 1
왼쪽) [m][n ~ j] 까지의 값 & m 번째 row 는 다 본거니까 m -= 1
위) [m ~ i][j] 까지의 값 & j 번째 column 은 다 본거니까 j += 1


55. Jump Game

https://leetcode.com/problems/jump-game/

My Answer 1: Accepted (Runtime: 480 ms - 72.33% / Memory Usage: 15.1 MB - 98.82%)

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        jump = nums[0]
        for i in range(len(nums)):
            if jump + nums[i] == 0 and i < len(nums)-1:
                return False
            if jump <= nums[i]:
                jump = nums[i]
            jump -= 1
        
        return True

모든 숫자들을 보면서 현재 점프 가능한 숫자보다 큰 값이 나오면 jump update

마지막 인덱스까지 가지 않았는데
jump + nums[i] == 0 이라서 더 갈 수 없다면 False

profile
Hello, World!

0개의 댓글

관련 채용 정보