Leetcode – 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.

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.

跟前一題一樣,給你一個陣列,代表的是每天的股票價格。這次你可以不斷買賣,但一次只能擁有一張

解法

  1. 做一個時光旅人,知道明天會漲,今天就買股票。知道明天會跌,且手上有股票,就賣掉
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let maxProfit = 0;
    let hold = null;
    let tomorrowPointer = 1;
    
    for(let i = 0 ; i < prices.length ;i++){
        
        console.log(i,'-',hold)
        
        // if last day then sell
        if(i == prices.length - 1 && hold != null){
            let profit = prices[i] - hold
            maxProfit += profit
            hold = null;
            continue
        }
        
        
        // if tomorrow is last day and price is fall
        if(i == prices.length - 2 && prices[tomorrowPointer] > prices[tomorrowPointer+1] && hold != null){

            let profit = prices[tomorrowPointer] - hold
            maxProfit += profit
            hold = null
            tomorrowPointer++;
            return maxProfit
        }
        
        
        // if tomorrow stock is raise
        if(prices[i] < prices[tomorrowPointer] && hold == null){
            hold = prices[i];
            tomorrowPointer++;
            continue
        }else if(prices[i] > prices[tomorrowPointer] && hold != null){
            let profit = prices[i] - hold
            maxProfit += profit
            tomorrowPointer++;
            hold = null
            continue
        }
        tomorrowPointer++;
        
        
    }
    return maxProfit
};

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。