Leetcode Best Time to Buy and Sell Stock

OpenSoucre發表於2014-06-24

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

一開始看到題目以為是最大值減去最小值即可,但由於買發生在賣前面,所以,最小值買進最大值賣出只有在最小值在最大值前面時才發生

本題思路是:遍歷時記錄前面最小值點,然後max(當前元素-前面最小值)即可

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() == 0) return 0;
        int res = 0, minv = prices[0];
        for(int i = 1; i < prices.size(); ++ i){
            res = max(res,prices[i]-minv);
            minv = min(prices[i],minv);
        }
        return res;
    }
};

本題也可以考慮利用動態規劃去做

設決策變數為dp[i],表示i個元素賣出的最大利潤

則狀態轉移方程為

  dp[i+1] = prices[i+1]-prices[i]+max(0,dp[i])

由於前面的dp[i],在dp[i+1]後不會被使用,故只需要一個狀態變數,不斷更新這個狀態變數即可

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int dp = 0, res = 0;
        for(int i = 1; i < prices.size(); ++ i){
            dp = prices[i]-prices[i-1] + max(0,dp);
            res = max(res,dp);
        }
        return res;
    }
};

 

 

相關文章