[ Top Interview 150 ] 122. Best Time to Buy and Sell Stock II

귀찮Lee·2023년 8월 24일
0

문제

122. 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 at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

  Find and return the maximum profit you can achieve.

  • Input : i번째 주식 가격을 담은 행렬 prices
  • Output : 주식을 여러번 사고 팔았을 때 얻을 수 있는 최대 이익
    • 하루에는 한 번 사거나 팔 수 있다. 여러 개가 아니라 한 개만 사고 팔 수 있다
    • 한 개를 샀으면 더 사지 못하고, 한 개를 팔았으면 더 이상 팔 수 없다.
    • 이익을 낼 수 없다면 0을 반환함

문제 풀이 전략

  • 기본 전략

    • 하향점이 끝나고 상향점으로 전환되기 전에 사고, 상향점이 끝나고 하향점으로 전환되기 전에 판다.
    • 아래의 도표를 보면 바로 전보다 가격이 올랐을 때는 무조건 이익이 되고, 그렇지 않은 경우에는 이익이 되지 않는다.
  • 문제 풀이 전략

    • prices를 순회함
      • 바로 이전보다 가격이 올랐을 경우 그 차이만큼을 이익에 더한다.

1차 풀이

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;

        for (int i = 1; i < prices.length; i++) {
            if (prices[i-1] < prices[i]) {
                profit += prices[i] - prices[i-1];
            }
        }

        return profit;
    }
}

profile
배운 것은 기록하자! / 오류 지적은 언제나 환영!

0개의 댓글