Leetcode--best time to Buy and Sell Stock

Source: Internet
Author: User

Only every time I look at this picture of the C + + does not have a white learning AH ~ ~ ~ usually with the time of the different Miss Eclipse, all kinds of nostalgia java~~~

This is the biggest profit, originally I think is to find the minimum and maximum, the difference is not the maximum profit, and then think, the minimum may be after the maximum value, can not be said to buy back in number 3rd to sell the stock and then think, record the minimum value before the day, and then record the maximum value after that day, Such a calculation will be able to calculate the maximum profit in a certain period of time, and then more than a few periods of profit, can calculate the ultimate maximum profit.

Class Solution {    //maxval[i] and Minval[i] represent the maximum value after I and the minimum before I, and then traverse one side to calculate the maximum profit public:    int Maxprofit (vector<int > &prices) {        if (Prices.empty ()) return 0;        const int size = Prices.size ();        int maxval[size], minval[size];        int Maxprofit (int_min);        Minval[0] = prices[0];        MAXVAL[SIZE-1] = prices[size-1];        for (int i = 1; i < size; I + +) {            Minval[i] = min (minval[i-1], prices[i]);        }        for (int i = size-2; I >= 0; I-) {            maxval[i] = max (maxval[i+1], prices[i]);        }        for (int i = 0; i < size; I + +) {            Maxprofit = max (Maxprofit, Maxval[i]-minval[i]);        }        return maxprofit;}    ;

Leetcode--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.