사는것이 파는것 보다 앞에 있어야 한다는 것 때문에 쉬운 문제임에도 투포인터로 삽질을 좀 했다.
class Solution {
public int maxProfit(int[] prices) {
int maxValue = 0;
int buyIndex = 0; // 매수할 날짜를 가리키는 포인터
for (int sellIndex = 1; sellIndex < prices.length; sellIndex++) {
if (prices[sellIndex] > prices[buyIndex]) {
// 현재 날짜에 매도하여 이익을 얻을 수 있는 경우
maxValue = Math.max(maxValue, prices[sellIndex] - prices[buyIndex]);
} else {
// 현재 날짜에 매수할 수 있는 경우
buyIndex = sellIndex;
}
}
return maxValue;
}
}
// int startIndex = 0;
// int endIndex = prices.length-1;
// int maxValue = 0;
// while(startIndex < endIndex){
// if(prices[startIndex]>=prices[startIndex+1]){
// startIndex++;
// }else if(prices[endIndex]<=prices[endIndex-1]){
// endIndex--;
// }else{
// maxValue = Math.max(maxValue, prices[endIndex] - prices[startIndex]);
// startIndex++;
// endIndex--;