Best Time to Buy and Sell Stock II
明确了上一题是求最大的连续子数组之和后。这题就更加简单了,遇到小于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 sum = 0; for(int i=0;i<n-1;i++) { if(diffs[i]>0) sum+=diffs[i]; } return sum; } }
posted on 2017-05-25 08:12 cynchanpin 阅读(147) 评论(0) 编辑 收藏 举报