Title:
Say you has an array for which the i-th element is the price of a given-stock on day I.
If you were-permitted-to-complete at most one transaction (ie, buy one and sell one share of the stock), design an AL Gorithm to find the maximum profit.
idea: A single scan can be. You just need to find the maximum growth . Max (prices[j]–prices[i]), I < J
From the point of travel, the current price minus the previous lowest price is the maximum profit that can be obtained by selling the stock at the current spot.
Scan, update the maximum profit and the lowest price.
Complexity: O (N)
AC Code:
Class Solution {public: int maxprofit (vector<int> &prices) { //traversal, Target finds a pair of lowest and highest points in sequence, making the maximum profit possible if (prices.size () <= 1) return 0; int low = prices[0]; int maxprofit = 0; for (int i = 1; i < prices.size (), i++) { int profit = prices[i]-low; if (Maxprofit < profit) Maxprofit = Profit; if (Prices[i] < low) low = Prices[i]; } return maxprofit;} ;
[C + +] leetcode:54 best time to Buy and Sell Stock