1.문제
Best Time to Buy and Sell Stock II - LeetCode
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
2.문제설명
전번 121번 문제와 비슷하나 조건이 하나 추가된다.
최대 1개의 주식을 가질 수 있고, 해당 주식을 구매한 날에 바로 팔 수 있다. 라는 조건이 하나 추가 되었다.
3.소스코드
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;
}
}
4.문제 해설
하루에 한번 주식을 사고 팔 수 있기 때문에 그 직전 값과 현재 값을 비교하여 직전 값보다 크면 차익을 계산하여 수익을 낼 수 있게 계산 하는 것이다