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).
這是一道貪心題谅辣,為了方便理解帅霜,我們可以吧每個(gè)元素的對(duì)應(yīng)的點(diǎn)值連起來(lái)畫(huà)成折線(xiàn)圖厅瞎,那么問(wèn)題就變成了在這一段一段的折線(xiàn)圖中怎么取可以取得最大的利潤(rùn)震叙。
顯然對(duì)于每一段能賺到錢(qián)的(即上升的折線(xiàn))線(xiàn)段,我們都是要去取得的(因?yàn)闆](méi)有次數(shù)限制)于是問(wèn)題就變成了判斷相鄰兩個(gè)點(diǎn)的折線(xiàn)是上升還是下降
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;
}
}