-
[array] best time to buy and sell stock 2Algorithm/LeetCode 2025. 4. 7. 09:43
✅ Problem
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
✅ Approach & Solution
방식) greedy 사용
더보기- 조건
- 최대 1개의 주식만 가지고 있을 수 있다.
- 같은 날에 주식을 사고 팔 수 있다.
- 최대 수익을 내려면 현재 값이 이전 값보다 큰 경우 무조건 팔아야 한다.
class Solution { public int maxProfit(int[] prices) { int maxProfit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i-1]) { maxProfit += (prices[i] - prices[i-1]); } } return maxProfit; } }
'Algorithm > LeetCode' 카테고리의 다른 글
[hash] jewels and stones (0) 2025.04.08 [array] maximum product subarray (0) 2025.04.06 [array] 3sum closest (0) 2025.04.05 [stack] valid parentheses (0) 2025.03.23 [array] container with most water (0) 2025.03.22 - 조건