首页 > 其他 > 详细

Best Time to Buy and Sell sock II

时间:2014-03-01 23:31:33      阅读:805      评论:0      收藏:0      [点我收藏+]

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

分析:本题的意思就是说你同一时间只能拥有一只股票,在一段时间呢最低时买进,最高时卖出,赚得利润最多。相当于给你一组数组,例如{1,2,3,4,0,2,3,1},在刚开始1时买进,到4时,下一个数字为0了,4是这段时间的最高价,应卖出,然后再买进循环下去,把所得差额加起来就是最大利润了。

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

python实现:

bubuko.com,布布扣
class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        nLen=len(prices)
        profit=0
        if nLen==0:
            return 0
        elif nLen<=1:
            return 0
        else:    
            for i in range(nLen-1):
                diff=prices[i+1]-prices[i]
                if diff>0:
                    profit+=diff
            return profit
bubuko.com,布布扣

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

Best Time to Buy and Sell sock II

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

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