Best Time to Buy and Sell Stock
Problem
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
Solution Approach
We only need to make atmost one transaction. Let say if we have purchased the stock on the day then the best day to sell it is on the day(after ) on which the stock has highest value.
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<int> dp(n);
dp[n - 1] = 0;
int mx = prices[n - 1];
int ans = 0;
for (int i = n - 2; i >= 0; i--) {
ans = max(ans, mx - prices[i]);
mx = max(mx, prices[i]);
}
return ans;
}
};