码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock

时间:2015-11-29 12:04:17      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Best Time to Buy and Sell Stock

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5004465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!