首页 > 其他 > 详细

Best Time to Buy and Sell Stock

时间:2014-03-18 12:04:07      阅读:444      评论: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.

思路:这道题就是让自己能得到最大的利润,举个例子{6,1,3,2,4,7},元素1和元素3得到利润为2,先保存起来,然后3到2少了1但是现在利润大于0,也是赚到了,后面一直到7,说明自己赚到(7-2)+(3-1)+(2-3)=6.所以每判断两个数相减如果大于0,则判断一次最大值;如果小于0,则将result置为0;

bubuko.com,布布扣
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int nSize=prices.size();
        if(nSize<=1)
            return 0;
        int result=0;
        int max=0;
        for(int i=1;i<nSize;i++)
        {
            result+=(prices[i]-prices[i-1]);
            if(result<0)
                result=0;
            if(max<result)
                max=result;
        }
        return max;
    }
};
bubuko.com,布布扣

Best Time to Buy and Sell Stock,布布扣,bubuko.com

Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/awy-blog/p/3606365.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!