Given a vector, the vector represents the price of a stock in the first day, Y to make the stock yield the largest should be bought on the day I, the first i+n days to sell, to find out the value of the maximum profit is how much
Idea: Record the minimum value with a variable, a variable record the maximum benefit, scan the price from beginning to end, when scanning to the price of the day I, if the price is smaller than the minimum value, then replace, if it is larger than the minimum value, then calculate whether the profit of the moment is greater than the maximum benefit, or the replacement, or continue.
class Solution {
public:
int maxProfit(vector<int> &prices) {
int profit = 0;
int minIndex = 0;
for (size_t i = 1; i < prices.size(); i++)
{
if (prices[i] < prices[minIndex])
{
minIndex = i;
}
else if (prices[i] - prices[minIndex] > profit)
{
profit = prices[i] - prices[minIndex];
}
}
return profit;
}
};
From for notes (Wiz)
best time to Buy and Sell Stock