public class S121 { public int maxProfit(int[] prices) { //TLE /* if(prices.length<2) return 0; int result = Integer.MIN_VALUE; for(int i = prices.length-1;i>0;i--){ prices[i] = prices[i]-prices[i-1]; } for(int i = 1;i<prices.length-1;i++){ int temp = 0; for(int j = i+1;j<prices.length;j++){ temp += prices[j]; if(temp>result) result = temp; } } return result;*/ //分治法--来自算法导论最大子数组问题,AC but slow ,move findCrossMax() inside findMax() makes 3ms quicker //not best /* if(prices.length<2) return 0; for(int i = prices.length-1;i>0;i--){ prices[i] = prices[i]-prices[i-1]; } int ret = findMax(prices,1,prices.length-1); return ret>0?ret:0; } public int findMax(int[] prices,int low,int high){ if(low==high){ return prices[low]; } int left = findMax(prices,low,(low+high)/2); int right = findMax(prices,(low+high)/2+1,high); // int mid = findCrossMax(prices,low,high); int leftResult = Integer.MIN_VALUE; int rightResult = Integer.MIN_VALUE; int temp = 0; for(int i = (low+high)/2;i>low-1;i--){ temp = temp+prices[i]; if(temp>leftResult){ leftResult = temp; } } temp = 0; for(int i = (low+high)/2+1;i<high+1;i++){ temp = temp+prices[i]; if(temp>rightResult){ rightResult = temp; } } int mid = leftResult+rightResult; return Math.max(left, Math.max(right, mid));*/
//better one from internet,omg!!!! i am stupid. /* if(prices.length<2) return 0; int curMin = prices[0]; int ret = Integer.MIN_VALUE; for(int i = 1;i<prices.length;i++){ curMin = Math.min(curMin, prices[i]); ret = Math.max(ret, prices[i]-curMin); } return ret;*/ //由053kadane's algorithm得到启发,this is the best one if(prices.length<2) return 0; int ret = Integer.MIN_VALUE; int sum = 0; for(int i = prices.length-1;i>0;i--){ prices[i] = prices[i]-prices[i-1]; if(sum<0) sum = 0; sum += prices[i]; if(sum>ret) ret = sum; } return ret>0?ret:0;
}
}