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