Say you have an array for which theithelement is the PRice of a given stock on dayi.
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).
這道題要注意幾點。首先profit算的是累積的,不是單個最大的。
然后就是題目上說了的,買股票之前必須要把股票賣完。所以說就不存在,只賣出一部分的情況。
這樣來說的話,其實算法比之前算單個max值的還要簡單一點。
代碼如下。~
public class Solution { public int maxProfit(int[] prices) { int profit=0; for(int i=1;i<prices.length;i++){ profit=profit+Math.max(0,prices[i]-prices[i-1]); } return profit; }}新聞熱點
疑難解答