Best Time to Buy and Sell Stock II - LeetCode
Can you solve this real interview question? Best Time to Buy and Sell Stock II - You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold
leetcode.com
📌 - 의사코드 및 풀이
Best Time To Buy And Sell Stock 1번 문제와 유사함
- result = 0 , max, min = prices[0] 으로 초기화
- 배열의 1번째 값 부터 마지막까지 for문
- i번째의 값보다 i-1번째의 값이 크면 result += max - min으로 업데이트 하고 max=min=prices[i] 값으로 변경
- 만약 prices[i] 값이 max보다 크면 max 값만 변경
- 처음에 틀렸던 부분중에 4번까지만 적용해서 하니까 [1,2,3,4,5] 경우 result에 더해주는 로직이 없어서 마지막에 return result 하기전에 result += max-min을 추가함
🔥 - Java 코드
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
int max = prices[0], min = prices[0];
for(int i= 1;i<prices.length;i++){
if(prices[i-1] > prices[i]){
result += max - min;
max = prices[i];
min = prices[i];
}
if(prices[i] > max){
max = prices[i];
}
}
result += max-min;
return result;
}
}