거의 알고리즘 일기장

[leetcode] - 121. Best Time to Buy and Sell Stock 본문

알고리즘 문제풀이

[leetcode] - 121. Best Time to Buy and Sell Stock

건우권 2023. 3. 31. 23:56

problem

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

 

Best Time to Buy and Sell Stock - LeetCode

Can you solve this real interview question? Best Time to Buy and Sell Stock - 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 choosin

leetcode.com

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.

Constraints:

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Access

1. brute force (O(n^2))

The problem has constraints 10^5. so, run loop 10^10 on a rough estimate.

I think this solution gets a timeout.

 

so, we need another solution as more efficient.

 

2. O(n)

We should buy cheap and sell expensive. and time has go direction.

ex) prices: [7,1,5,3,6,4]
7 -> 1 -> 5 -> 3 -> 6 -> 4

We just need the lowest price, when current day.

and we calculate the current price - min price until previous.

function maxProfit(prices: number[]): number {
    let result = 0;
    let min = 10000;

    for(let i=0; i<prices.length; i++){
        //currentPrice - minPrice until previous
        const currentPrice = prices[i];
        result = Math.max(result, currentPrice-min);
        
        //and save minPrice until current
        min = Math.min(min, currentPrice);
    }
    
    //this result is max profit, because all case calcurate and compare in previous loop function
    return result;
};

반응형

'알고리즘 문제풀이' 카테고리의 다른 글

[leetcode] - 217. Contains Duplicate  (0) 2023.04.01
[leetCode] - 1. Two Sum -  (0) 2023.03.31
백준 1175번 _ 배달  (2) 2020.11.07
백준 1194번 _ 달이 차오른다, 가자.  (0) 2020.11.07
백준 5373번 _ 큐빙  (0) 2020.11.07
Comments