您的位置:首页 > 其它

leetcode122 Best Time to Buy and Sell Stock II

2015-11-06 19:18 477 查看
我的leetcode代码在github地址:https://github.com/gaohongbin/leetcode

题目:

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).

Subscribe to see which companies asked this question

翻译:
这个题和leetcode121 Best Time to Buy and Sell Stock差不多,只是leetcode121 Best Time to Buy and Sell Stock只能完成一次交易,而leetcode122 Best Time to Buy and Sell Stock II可以完成多次交易。求出最大的收益。

思路:

这个题刚开始没有思路,在纸上画一画我们可能有点思路了,我自己的思路是这样的。

如果数组是2,4,5,8这种递增的数组,则8-2就是能得到的最大利润。

如果数组为2,5,4,8这种数组,则(5-2)+(8-4)就是得到的最大利润,如果一个数组在递增的过程突然不再递增,则就可以进行一次交易了。

如果数组为4,3,2,5这种数组,则在递减到最低点时买入,在相邻的一个最高点卖出。

根据这个思路,我写下了如下的代码:

代码:

public int maxProfit(int[] prices) {
int length=prices.length;
if(prices==null || length<2)
return 0;

int maxProfit=0;
int price=prices[0];
int lastSellPrice=prices[0];
for(int i=1;i<length;i++){
if(prices[i]>price){
if(prices[i]>lastSellPrice)
lastSellPrice=prices[i];
if(prices[i]<lastSellPrice){
maxProfit+=lastSellPrice-price;
price=prices[i];
lastSellPrice=price;
}
}
if(prices[i]<=price){
if(lastSellPrice>price){
maxProfit+=lastSellPrice-price;
price=prices[i];
lastSellPrice=price;
}
if(lastSellPrice==price){
price=prices[i];
lastSellPrice=price;
}
}
}
maxProfit+=lastSellPrice-price;
return maxProfit;

}


但是最后运行以后才击败了6.2%的代码,发现还有另外一个代码,感觉很精练,最后才发现自己的代码最终实现的也是这样的功能。

public int maxProfit(int[] prices) {
if (prices.length < 2) return 0;

int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
int diff = prices[i] - prices[i - 1];
if (diff > 0) {
maxProfit += diff;
}
}

return maxProfit;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode