Greedy+Array. Easy mode.我的解法太啰嗦了,标准答案才是真正用到了“greedy”的精髓。
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 class Solution {
public int maxProfit(int[] prices) {
//[7, 1, 5, 3, 6, 4]
if(prices.length<2 || prices==null) return 0;
int profitSoFar, profitCur, buySoFar, sellSoFar;
buySoFar=prices[0];
profitSoFar=profitCur=sellSoFar=0;
boolean isSold=false;
for(int i=1; i<prices.length; i++){
if(!isSold){
if(buySoFar>=prices[i])
buySoFar=prices[i];
else
{ profitCur=prices[i]-buySoFar;
isSold=true;
sellSoFar=prices[i];
}
}
else{
if(prices[i]<sellSoFar){
isSold=false;
buySoFar=prices[i];
profitSoFar+=profitCur;
profitCur=0;
}else{
sellSoFar=prices[i];
profitCur=prices[i]-buySoFar;
}
}
}
profitSoFar+=profitCur;
return profitSoFar;
}
}
Approach #3 (Simple One Pass)
[1, 7, 2, 3, 6, 7, 6, 7]
The graph corresponding to this array is:
From the above graph, we can observe that the sum A+B+C is equal to the difference D corresponding to the difference between the heights of the consecutive peak and valley.
class Solution {
public int maxProfit(int[] prices) {
int maxprofit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1])
maxprofit += prices[i] - prices[i - 1];
}
return maxprofit;
}
}