Leetcode 121 best time to Buy and Sell Stock

Source: Internet
Author: User

 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&LT;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.