문제링크 - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
class Solution {
public int maxProfit(int[] prices) {
int buyIndex = 0; // 매수 인덱스
int sellIndex = 0; // 매도 인덱스
int maxProfit = 0; // 이익
// 매도 인덱스를 증가시킨다.
for (int i = 0; i < prices.length - 1; i++) {
// 파려는 날짜 다음이 더 비싸거나 같으면 매도를 미룬다
if (prices[sellIndex] <= prices[sellIndex + 1]) {
// 다음날에 팔도록
sellIndex++;
// 매도 값이 다음날보다 크다
} else if (prices[sellIndex] > prices[sellIndex + 1]) {
// 판매하여 이익.
if (sellIndex > buyIndex) {
maxProfit += prices[sellIndex] - prices[buyIndex];
}
// 다음날 매수한 것으로 인덱스 초기화
buyIndex = sellIndex + 1;
sellIndex = sellIndex + 1;
}
}
// 반복문이 끝나도 매수했으면 남은 주식 매도.
if (sellIndex > buyIndex) {
maxProfit += prices[sellIndex] - prices[buyIndex];
}
return maxProfit;
}
}