LeetCode 121 Best Time to Buy and Sell Stock
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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Example 2:
c++
class Solution { public: int maxProfit(vector<int>& prices) { int minx = 9999999; int ans = 0; int l = prices.size(); for(int i=0;i<l;i++) { minx = min(minx,prices[i]); ans = max(ans,prices[i]-minx); } return ans; } };