https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
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 문제는 익숙~
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
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
) 보다 큰 값이 나오면 냅다 팔아버리기
https://leetcode.com/problems/spiral-matrix/
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
https://leetcode.com/problems/jump-game/
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