您的位置:首页 > 其它

50.Best Time to Buy and Sell Stock II(贪心算法)

2016-01-05 16:00 267 查看
题目原文:

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

分析:题目要求解是给定一个价格数组,然后设定算法对股票进行多次买卖操作,最终取得最大的利益。并且要求买一定要在卖的操作之前。

做这个题目的思路是用贪心的思想,选择价格数组中所有所有上涨价格段之和。即求价格曲线中所有价格上升段的长度之和。

代码如下:

/*可以允许买卖多次,采用贪心的策略*/
public int maxProfit(int[] prices) {
int sum=0;//待返回的利益
int len = prices.length;
for(int i =1;i<len;i++){
/*第i天的价格大于第i-1天的价格的时候,则第i-1天买,第i天卖*/
if(prices[i-1]<prices[i]){
sum += prices[i]-prices[i-1];
}
}
return sum;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: