Best purchase time: 121

Source: Internet
Author: User

Question:

Assume that you have an array whereIItemsElement isIThe price of the given stock per day.

If you are only allowed to complete up to one transaction (that is, to buy and sell one stock), design an algorithm to find the maximum profit.

Analysis:

This problem is generally due to the I and j double-digit groups used for query and calculation. However, we can look for the smallest number in the first I segment as the purchase point, then we sell the product on the I day, so we can reduce the dimensionality. The idea of this question is to face I, when J is a two-dimensional variable, we need to think about whether we can fix a variable by dimensionality reduction (usually j) and convert it into a one-dimensional DP.

Code:

Int maxprofit (vector <int> & prices) {const int n = prices. size (); If (n <1) return 0; vector <int> min_prices (n); vector <int> max_profit (N ); min_prices [0] = Prices [0]; max_profit [0] = 0;
// Scroll to the minimum number of days before the migration to achieve dimensionality reduction (INT I = 1; I <n; ++ I) {min_prices [I] = min (min_prices [I-1], Prices [I]); max_profit [I] = max (max_profit [I-1], prices [I]-min_prices [I-1]);} return max_profit [n-1];}

Best purchase time: 121

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.