知道是求连续最大子数组后就简单了。可是注意边界条件,假设最大子数组之和<0,那就不要交易了, 返回0.
public class Solution { public int maxProfit(int[] prices) { if(prices.length < 2) return 0; int n = prices.length; int[] diffs = new int[n]; for(int i=0;i<n-1;i++) diffs[i] = prices[i+1] - prices[i]; int csum = 0; int maxsum = 0; for(int i=0;i<n-1;i++) { csum += diffs[i]; if(csum > maxsum) maxsum = csum; if(csum < 0) csum = 0; } return maxsum; } }