假設有一個數組,它的第i個元素是一個給定的股票在第i天的價格。設計一個算法來找到最大的利潤。你可以完成儘可能多的交易(多次買賣股票)。然而,你不能同時參與多個交易(你必須在再次購買前出售股票)。
給出一個數組樣例[2,1,2,0,1], 返回 2
開始以爲只是數組中最大的減去最小的,不知道要不要看先後順序,不過既然是按天數,所以應該是要的,而且題目說是多次操作,嘗試了下數據[11,2,1,2,3,1,0,4]輸出的是6,所以應該是按天數遞增然後多次操作後的結果。
這中等題比容易的還容易
class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
int profits = 0;
for (int i = 0;i < prices.length-1 ; i++){
int profit = prices[i+1]-prices[i];
if(profit > 0){
profits+=profit;
}
}
return profits;
}
};