LeetCode 121 Best Time to Buy and Buy Stock resolution (the Best Time to Buy and Sell stocks)
Translation
In other words, you have an array where the I-th element indicates the stock price on the I-th day. If you are only allowed to trade at most once (for example, buy and sell a stock), design an algorithm and find the maximum profit.
Original
Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Analysis
First, set the maximum profit and minimum profit:
If the current day's stock price is lower than the lowest price, set the lowest price to the day's stock price.
The reason is that we have to calculate the price is, of course, paving the way for the maximum profit.
If the maximum profit is lower than the minimum price for the current day, set the maximum profit to the current day price minus the lowest price.
Code
class Solution {public: int maxProfit(vector
& prices) { size_t size = prices.size(); if (size <= 1) return 0; int min = INT_MAX, max = INT_MIN; for (int i = 0; i < size; ++i) { if (prices[i] < min) min = prices[i]; if (max < prices[i] - min) max = prices[i] - min; } return max; }};