-
[LeetCode] 122. Best Time to Buy and Sell Stock IILeetCode 2021. 10. 16. 23:23728x90
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Best Time to Buy and Sell Stock II - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Best Time to Buy and Sell Stock II

주식 사고팔기 두번째 시리즈이다.
첫번째 시리즈를 먼저 풀고 푸는걸 권한다.
번외 시리즈는 이 시리즈를 다 풀고 풀는걸 권한다.
첫번째 시리즈
https://kohsmos.tistory.com/59
[LeetCode] 121. Best Time to Buy and Sell Stock
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ Best Time to Buy and Sell Stock - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your kn..
kohsmos.tistory.com
+ 번외 시리즈
https://kohsmos.tistory.com/56
[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ Best Time to Buy and Sell Stock with Cooldown - LeetCode Level up your coding skills and quickly land a job. This is the..
kohsmos.tistory.com
두번째 시리즈 문제는 평범하게 주식을 사고 파는 것이다.
번외 시리즈를 먼저 접했기에 이 시리즈가 간단해졌다.
원하는 날 사고, 원하는날 팔면 된다.
이 때 최대 수익을 구하는 문제다.
주식을 갖고 있는 상태를 stock_y로 놓고
주식을 갖고 있지 않은 상태를 stock_n로 놓자.
그렇다면 stock_y 상태는 stock_y에서 쭉 유지할 경우와 stock_n에서 그날 주식을 샀을때 가능한 상태고,
stock_n 상태는 stock_n에서 쭉 유지할 겨웅와 stock_y에서 그날 주식을 팔았을때 가능한 상태다.
이를 이용해 최대값을 구하는 식을 세우면,
stock_y = max(stock_y, stock_n-price)
stock_n = max(stock_n, stock_y+price)
이렇게 구할 수 있다.
아래는 전체 풀이코드다.
class Solution { public: int maxProfit(vector<int>& prices) { int stock_y=INT_MIN, stock_n = 0, temp; for (int price:prices) { temp= stock_y; stock_y = max(stock_y, stock_n-price); stock_n = max(stock_n, temp+price); } return max(stock_y, stock_n); } };'LeetCode' 카테고리의 다른 글
[LeetCode] 188. Best Time to Buy and Sell Stock IV (0) 2021.10.16 [LeetCode] 123. Best Time to Buy and Sell Stock III (0) 2021.10.16 [LeetCode] 121. Best Time to Buy and Sell Stock (0) 2021.10.16 [LeetCode] 1869. Longer Contiguous Segments of Ones than Zeros (0) 2021.10.15 [LeetCode] 1961. Check If String Is a Prefix of Array (0) 2021.10.15