[LeetCode/Top Interview 150] [Array / String] 122. Best Time to Buy and Sell Stock II

1vl·2023년 8월 24일
0

문제 링크: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
사용 언어: Java(OpenJDK 17. Java 8)

난이도: medium

문제:

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.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

Constraints:

1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104

전략:

이전 문제와 유사하지만 이제 사고팔기가 가능해졌다.
최대 보유할 수 있는 주식 수는 여전히 하나이고, 같은 날에 사고팔아도 괜찮다 -> 오늘 가격이 최고가액이라면 오늘 사자마자 팔고 내일부터 수익을 노린다는 개념으로 가면 좋을 듯.

주식으로 이득을 보기 위해서는 수익이 나는 모든 순간에 팔고, 내일 손실이 예상되면 오늘 판 것으로 처리하면 되지 않을까?

코드 구현:

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i=1;i<prices.length;i++) {
            int diff = prices[i] - prices[i-1];
            if (diff > 0) {
                profit+=diff;
            }
        }
        return profit;
    }
}

실행결과:
Time: 0 ms (100.00%), Space: 43.8 MB (98.89%) - LeetHub
https://github.com/1-vL/LeetCode/blob/main/0122-best-time-to-buy-and-sell-stock-ii/0122-best-time-to-buy-and-sell-stock-ii.java

개선 방안:

딱히 더 나은 개선방안은 떠오르지 않는다. 문제 난이도가 잘못 표기된 것이 아닌가 싶을 만큼 간단했다.

Discuss 탭의 타인 코드:

class Solution {
    public int maxProfit(int[] prices) {
        int profit=0;
        for(int i=1; i<prices.length; i++){
            if(prices[i]>prices[i-1]){
                profit+=prices[i]-prices[i-1];
            }
        }
        return profit;
    }
}

// 역시나 자신 있던 만큼 다른 사람들의 코드를 봐도 거의 동일한 코드다.
	Accepted	0 ms	44.1 MB	java

회고:
주식 사고팔기 문제는 순서가 서로 바뀌는게 보다 난이도에는 맞는 것이 아닌가 하는 생각이 든다.
실제 주식처럼 사고 파는 과정에서 수수료가 발생한다는 문제였으면 더 어려웠을 듯.

profile
React-Native, Flutter, Java, Spring, lua

0개의 댓글