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=;
int diff;
int nLength=prices.size();
for(int i=;i<nLength;++i)
{
diff=prices[i]-prices[i-];
if(diff>=)
{
profit+=diff;
}
}
return profit;
}
};

python实现:

class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
nLen=len(prices)
profit=
if nLen==:
return
elif nLen<=:
return
else:
for i in range(nLen-):
diff=prices[i+]-prices[i]
if diff>:
profit+=diff
return profit
上一篇:Log4j appender输出类型配置


下一篇:JavaScript实现回车键切换输入框焦点