Public classS121 { Public intMaxprofit (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;*/ //divide and conquer Method--from the introduction of algorithm maximum Subarray problem, 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*/ // Best One if(prices.length<2) return0; intCurmin = Prices[0]; intRET =Integer.min_value; for(inti = 1;i<prices.length;i++) {curmin=math.min (Curmin, prices[i]); RET= Math.max (ret, prices[i]-curmin); } returnret; } }
Leetcode 121 best time to Buy and Sell Stock