Leetcode 121. Best Time to Buy and Sell Stock
You are given an array prices
where prices[i]
is the price of a given stock on the i-th
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.
Example:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
The goal is to find the maximum difference between a future selling price and a past buying price. We can achieve this by maintaining a minimum price seen so far and checking the potential profit at each step.
Steps:
#include <vector>
#include <algorithm>
#include <iostream>
class Solution {
public:
int maxProfit(std::vector<int>& prices) {
if (prices.empty()) return 0; // handle the edge case of an empty array
int minPrice = INT_MAX; // Initialize minPrice to a very high value
int maxProfit = 0; // Initialize maxProfit to zero
for (int price : prices) {
if (price < minPrice) {
minPrice = price; // Update the minimum price
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice; // Update the maximum profit
}
}
return maxProfit;
}
};
int main() {
Solution sol;
std::vector<int> prices = {7, 1, 5, 3, 6, 4};
std::cout << "Max Profit: " << sol.maxProfit(prices) << std::endl; // Output: 5
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?