Leetcode--best time to Buy and Sell Stock II

Source: Internet
Author: User

Traverse the price vector, add up the profit for each period of the ascent, and remember to calculate the last profit at the end.

Class Solution {    //Add up profit for each period of ascent    //Minval: Trough value    //maxval: Peak    //Profit: Profit public:    int Maxprofit ( Vector<int> &prices) {        if (Prices.empty ()) return 0;        int maxval (prices[0]), Minval (Prices[0]), profit (0);        for (int i = 0; I! = Prices.size (); i + +) {            //If down, sell stock: if prices[i] > maxval, then Drop            if (Prices[i] < maxval) {
   
    profit + = Maxval-minval;                Minval = Maxval = Prices[i];            }            If up, change the peak            else{                maxval = prices[i];            }        }        Finally calculate the profit again, if Maxval-minval > 0, then add profit        if (Maxval-minval > 0) Profit + = Maxval-minval;        return profit;}            ;
   

Leetcode--best time to Buy and Sell Stock II

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.