Leetcode best time to buy and Sell stock trading stock (DP)

Source: Internet
Author: User

Test instructions: Given a sequence, the element I represents the price of this stock for the first day, asking how much money can be earned at the best time to buy and sell? Buy only once, and only 1 shares, assuming unlimited cost.

Idea: To find a low-priced time to buy, at the highest price when the sale of profits will be the biggest. But time is not a conflict, for example buy tomorrow, sell today. Therefore, for today's price, we should find the lowest price of the stock before today, buy, sell today.

In fact, for one element in the sequence a[k], find another element a[e], the position satisfies e<k, the result makes a[k]-a[e] maximum.

With dynamic planning, the current minimum value is updated with an element from left sweep, and the current element is used to reduce the minimum value. We'll know the result after sweep.

classSolution { Public:    intMaxprofit (vector<int>&prices) {        intSmall=2147483647, ans=0;  for(intI=0; I<prices.size (); i++) {Small=min (small, prices[i]);//find the minimum value before IAns=max (prices[i]-small, ans); }        returnans; }};
AC Code

Leetcode best time to buy and Sell stock trading stock (DP)

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.