[leetcode #121] Best Time to Buy and Sell Stock

Seongyeol Shin·2022년 2월 3일
0

leetcode

목록 보기
144/196
post-thumbnail
post-custom-banner

Problem

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

・ 1 <= prices.length <= 10⁵
・ 0 <= prices[i] <= 10⁴

Idea

dp를 이용해 쉽게 풀 수 있는 문제다. 주어진 배열의 길이가 최대 10⁵가 될 수 있으므로 O(n²)으로 풀면 Time Limit Exceeded에 걸린다.

dp 배열의 크기는 2로 하고, 0번째 index 값은 주식을 들고 있지 않을 때 최대값, 1번째 index 값은 주식을 들고 있을 때 최대값으로 설정한다. 주식 배열을 돌 때마다 dp[0]을 최대값과 비교해 더 크면 최대값으로 바꿔준다.

Time Complexity: O(n)
Space Complexity: O(1)

Solution

class Solution {
    public int maxProfit(int[] prices) {
        int[] dp = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
        int res = 0;

        for (int price : prices) {
            dp[0] = Math.max(price + dp[1], res);
            dp[1] = Math.max(-price, dp[1]);
            res = Math.max(dp[0], res);
        }

        return res;
    }
}

Reference

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

profile
서버개발자 토모입니다
post-custom-banner

0개의 댓글