min = 배열의 첫째항;
diff = 차이;
total = 차이들의 합;
for(1,길이,1증가){
if:diff가 값 - min 보다 크면 (오름 차순 중단)
-> min에 값을 저장
-> total에 diff 더함
-> diff를 0으로 리셋
else: (오름 차순 진행)
-> diff에 차이 값 저장
}
return total값에 마지막으로 diff 더해줌.
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int min = prices[0];
int diff = 0;
int total = 0;
for(int i = 1; i < len; i++){
int tmp = prices[i] - min;
if(diff > tmp){
min = prices[i];
total += diff;
diff = 0;
}else{
diff = tmp;
}
}
return total + diff;
}
}
O(n)
O(1)
O(n)
O(1)
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int min = prices[0];
int total = 0;
for(int i = 1; i < len; i++){
if(prices[i] > min){ //오름차순인 구간에서 오름차순이 끝날 때까지두 수의 차를 더 해주면, 처음과 마지막 값의 차와 동일하다.
total += prices[i] - min;
min = prices[i];
}else{
min = prices[i];
}
}
return total;
}
}
오름차순일 경우, 예를 들어, 1,4,5 => 5-1 == 4-1 + 5-4 가 성립된다는 것을 문제풀 때, 생각을 하지 못했습니다.