贪心策略:
只要能获得正收益,我就交易。
实现方法1:双指针。
public class solution {
public int maxProfit(int[]prices){
int ret=0,n= prices.length;
for(int i=0;i<n;i++){
int j=i;
while(j+1<n&&prices[j]<prices[j+1])j++;
ret+=prices[j]-prices[i];
i=j;
}
return ret;
}
public static void main(String[] args) {
solution solution=new solution();
int[] prices={7, 1, 5, 3, 6, 4};
System.out.println(solution.maxProfit(prices));
}
}
实现方法2:拆分成一天一天的形式。
public class Solution2 {
public int maxProfit(int[]prices){
int ret=0;
for(int i=1;i< prices.length;i++)
{
if(prices[i]>prices[i-1])
{
ret+=prices[i]-prices[i-1];
}
}
return ret;
}
public static void main(String[] args) {
Solution2 solution2=new Solution2();
int [] prices={7,1,5,3,6,4};
System.out.println(solution2.maxProfit(prices));
}
}