Leetcode Best Time to Buy and Sell Stock

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;
    }
};

 

 

posted @ 2014-06-24 20:13  OpenSoucre  阅读(150)  评论(0编辑  收藏  举报