Best Time to Buy and Sell sock II

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是这段时间的最高价,应卖出,然后再买进循环下去,把所得差额加起来就是最大利润了。

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

python实现:

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

 

posted @ 2014-03-01 09:44  Awy  阅读(282)  评论(0编辑  收藏  举报