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

来源:互联网 发布:c语言和指针下载 编辑:程序博客网 时间:2024/06/17 08:20

题目原文:

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


0 0