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.

算法导论原题,股票买入卖出的最大利益-->数组中后面的元素与前面的元素的最大差值-->转换为连续子数组最大和

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

 

posted @ 2015-11-29 11:18  zengzy  阅读(165)  评论(0编辑  收藏  举报
levels of contents