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).
这是一道贪心题,为了方便理解,我们可以吧每个元素的对应的点值连起来画成折线图,那么问题就变成了在这一段一段的折线图中怎么取可以取得最大的利润。
显然对于每一段能赚到钱的(即上升的折线)线段,我们都是要去取得的(因为没有次数限制)于是问题就变成了判断相邻两个点的折线是上升还是下降
class Solution {
public int maxProfit(int[] prices) {
int max = 0 ;
for(int i = 0 ;i<prices.length-1;i++)
{
if(prices[i]<prices[i+1])
{
max+=(prices[i+1]-prices[i]);
}
}
return max;
}
}
网友评论