-
[LeetCode] 121. Best Time to Buy and Sell StockLeetCode 2021. 10. 16. 23:14728x90
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 knowledge and get prepared for your next interview.
leetcode.com
Best Time to Buy and Sell Stock

오늘 문제가 이 문제에서 파생된 문제이기에 먼저 풀어보았다.
전에 푼 문제와 비슷하다.
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
어떤 특정한 날 주식을 사서 특정한 날 주식을 팔았을 때 얻을 수 있는 최대 수익을 구하는 문제이다.
주식을 사고 파는 행위는 딱 한번만 가능하다.
딱 한번만 사고 팔면 되므로 매우 간단했다.
그날의 주식가격에 그 앞날의 가격들중 최소값을 빼준게 최대가 되는 값을 찾아주면 된다.
최소값 m과 최대값 M을 만들고, prices를 쭉 훑으며 price 최소가 될때 m을 저장해주고, price-m이 최대가 될때 M을 저장해준다.
마지막으로 M을 리턴해주자.
전체풀이코드
class Solution { public: int maxProfit(vector<int>& prices) { int m=INT_MAX,M=INT_MIN; for (int price:prices) { m = min(price, m); M = max(price-m,M); } return M; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 123. Best Time to Buy and Sell Stock III (0) 2021.10.16 [LeetCode] 122. Best Time to Buy and Sell Stock II (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 [LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown (0) 2021.10.15