Buy and Sell Stocks

Problem Statement
You are given an array prices[]
where prices[i]
represents the price of a stock on the i
-th day. You need to find the maximum profit you can achieve by buying and selling the stock at most once. If no profit can be made, 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
.
Approach
Initialize Variables:
Maintain
min_price
to track the lowest price seen so far.Maintain
max_profit
to store the maximum possible profit.
Iterate Through Prices:
If the current price is lower than
min_price
, updatemin_price
.Calculate the profit by subtracting
min_price
from the current price.Update
max_profit
if the calculated profit is greater thanmax_profit
.
Return
max_profit
after traversing the array.
Code implementation:
int maxProfit(vector<int>& prices) {
int i,minEle=prices[0],cost,profit=0;
for(i=0;i<prices.size();i++){
cost=(prices[i]-minEle);
profit=max(profit,cost);
minEle=min(prices[i],minEle);
}
return profit;
}
Time and Space Complexity
Time Complexity:
O(n)
, since we traverse the array once.Space Complexity:
O(1)
, as we use only two extra variables.
Edge Cases Considered
When prices are decreasing, e.g.,
[7,6,4,3,1]
, output should be0
.When prices have only one element, output should be
0
.When prices array is empty, output should be
0
.
problem link:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Subscribe to my newsletter
Read articles from Nikhitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nikhitha
Nikhitha
๐ Software Developer | DSA Enthusiast | Problem Solver ๐น Sharing daily DSA solutions, coding insights, and interview prep ๐น Passionate about writing optimized & bug-free code