[Leetcode] Best time to Buy Stock

Source: Internet
Author: User

Consider that the price of a stock is constantly changing, and selling can only be done after buying. and can only buy and sell once.

I want to sweep it at the beginning and ask for the smallest, but certainly not so simple. you're 484 stupid .

Because it can only be sold once, if I sell, the possible profit value is, Prices[i]-min, is today's price.

Comparing this value to the previous possible maximum, you can get the maximum possible value for the first day.

Class Solution {public:    int Maxprofit (vector<int>& prices) {        if (prices.size () <= 1) return 0;        int minprice = prices[0];        int n = prices.size ();                int maxprofit = 0;                for (int i =0; i<n; ++i) {            minprice = min (Minprice, prices[i]);            Maxprofit = Max (Maxprofit,prices[i]-minprice);        }                return maxprofit;}    ;

  

[Leetcode] Best time to Buy 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.