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.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


思路:动态规划+从前到后

第一种方法是:从前往后,如果比之前最小的还小,替代他,并且用ans保存当前与最小值的大小,每一次只需要判断是否比最小值小,要么就是判断与之前的最小值比较是否比ans大。

第二种方法以后再更新。


代码:

//本题只能买卖1次,从前到后
//写出了两种解法。
class Solution1 {
public:
//https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
    int maxProfit(vector<int>& prices) {
        
        int ans=0;
        if(prices.empty()){
            return 0;
        }
        int low=prices[0];
        for(int i=1;i<prices.size();i++){
            if(prices[i]<low){
                low=prices[i];
            }else if(prices[i]-low>ans){
                ans=prices[i]-low;
            }
        }
        return ans;
    }
};

 class Solution2 {
 public:
     int maxProfit(vector<int> &prices) {
         int length=prices.size();
         if(length<=1){
             return 0;
         }
         vector<int> dp(length,0);
         int min=prices[0];
         for(int i=1;i<length;i++){
             if(prices[i]<=min){
                 min=prices[i];
             }
             dp[i]=max(  dp[i-1],prices[i]-min   );
         }
         sort(dp.begin(),dp.end());
         return dp.back();
     }
 };
 
 //dp[i] 表示[0...i]内最大值,则dp[i+1]=max(dp[i],prices[i+1]-min)
 //min是[0...i]内的最小值


posted @ 2015-10-12 00:19  JSRGFJZ6  阅读(144)  评论(0编辑  收藏  举报