标签:blog io java for 2014 on log new as
知道是求连续最大子数组后就简单了。但是注意边界条件,如果最大子数组之和<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; } }
Leetcode - Best Time to Buy and Sell Stock
标签:blog io java for 2014 on log new as
原文地址:http://blog.csdn.net/tspatial_thunder/article/details/40227365