Problem Statement
Given an array prices[]
where prices[i]
represents the price of a stock on the ith day, we need to find the maximum profit that can be obtained by making a single buy-sell transaction.
In other words, we need to find the maximum difference prices[j] - prices[i]
where i < j
.
Examples:
Example 1:
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
Example 2:
Input: prices[] = {7, 6, 4, 3, 1}
Output: 0
Explanation: In this case, no transaction is done, i.e., max profit = 0
Different Approaches
1️⃣ Brute Force Approach
Intuition:
Algorithm:
- Iterate through each day
i
from0
ton - 1
, wheren
is the size of the input array. - For each day
i
, iterate through each subsequent dayj
fromi + 1
ton - 1
. - Calculate the profit
prices[j] - profit[i]
for each pair of days(i, j)
. - Keep track of the maximum profit found so far.
- Finally, return the maximum profit obtained after iterating through all possible pairs.
Code:
#include<bits/stdc++.h>
using namespace std;
int maxProfit(vector<int> &arr) {
int maxPro = 0;
int n = arr.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[i]) {
maxPro = max(arr[j] - arr[i], maxPro);
}
}
}
return maxPro;
}
int main() {
vector<int> arr = {7,1,5,3,6,4};
int maxPro = maxProfit(arr);
cout << "Max profit is: " << maxPro << endl;
}
Complexity Analysis:
- Time Complexity:
O(N ^ 2)
- Space Complexity:
O(1)
2️⃣ Optimal Approach
Intuition:
The problem can be reduced to finding the minimum price to buy the stock and the maximum price to sell the stock afterward. We need to keep track of the minimum price we’ve encountered so far and calculate the profit we would get by selling the stock on the current day. Our goal is to maximize this profit.
By traversing the array linearly, we maintain a variable to store the minimum price encountered so far. As we move forward in the array, we compare each element with this minimum. If the current element is greater than the minimum, we update the maximum profit if the difference between the current element and the minimum is greater than the previously recorded maximum profit. Otherwise, we update the minimum price encountered.
Algorithm:
- Initialize two variables:
minPrice
: To keep track of the lowest stock price seen so far.maxProfit
: To store the maximum profit possible.
- Traverse through the prices array:
- For each day, check if the current price is less than
minPrice
. If so, updateminPrice
. - Calculate the potential profit if we sell the stock on the current day (
current price - minPrice
). - Update
maxProfit
if the calculated profit is greater than the previous maximum profit.
- For each day, check if the current price is less than
- At the end of the traversal,
maxProfit
will contain the maximum profit that can be made by one buy-sell transaction.
Dry Run:
Initialization:
+-----+-----+-----+-----+-----+-----+
prices = | 7 | 1 | 5 | 3 | 6 | 4 |
+-----+-----+-----+-----+-----+-----+
minPrice = 7
maxProfit = 0
Iteration 1:
+-----+-----+-----+-----+-----+-----+
prices = | 7 | 1 | 5 | 3 | 6 | 4 |
+-----+-----+-----+-----+-----+-----+
^
|
i
minPrice = 7
maxProfit = 0
prices[i] < minPrice
1 < 7
True,
Update minPrice to prices[i]
minPrice = 1
Iteration 2:
+-----+-----+-----+-----+-----+-----+
prices = | 7 | 1 | 5 | 3 | 6 | 4 |
+-----+-----+-----+-----+-----+-----+
^
|
i
minPrice = 1
maxProfit = 0
prices[i] < minPrice
5 < 1
False
Else Calculate maxProfit if we sell today
maxProfit = max(prices[i] - minPrice, maxProfit)
= max(5 - 1, 0)
= max(4, 0)
= 4
Iteration 3:
+-----+-----+-----+-----+-----+-----+
prices = | 7 | 1 | 5 | 3 | 6 | 4 |
+-----+-----+-----+-----+-----+-----+
^
|
i
minPrice = 1
maxProfit = 4
prices[i] < minPrice
3 < 1
False
Else Calculate maxProfit if we sell today
maxProfit = max(prices[i] - minPrice, maxProfit)
= max(3 - 1, 4)
= max(2, 4)
= 4
Iteration 4:
+-----+-----+-----+-----+-----+-----+
prices = | 7 | 1 | 5 | 3 | 6 | 4 |
+-----+-----+-----+-----+-----+-----+
^
|
i
minPrice = 1
maxProfit = 4
prices[i] < minPrice
6 < 1
False
Else Calculate maxProfit if we sell today
maxProfit = max(prices[i] - minPrice, maxProfit)
= max(6 - 1, 4)
= max(5, 4)
= 5
Iteration 5:
+-----+-----+-----+-----+-----+-----+
prices = | 7 | 1 | 5 | 3 | 6 | 4 |
+-----+-----+-----+-----+-----+-----+
^
|
i
minPrice = 1
maxProfit = 5
prices[i] < minPrice
4 < 1
False
Else Calculate maxProfit if we sell today
maxProfit = max(prices[i] - minPrice, maxProfit)
= max(4 - 1, 5)
= max(3, 5)
= 5
Iteration 6 (Loop Termination):
+-----+-----+-----+-----+-----+-----+
prices = | 7 | 1 | 5 | 3 | 6 | 4 |
+-----+-----+-----+-----+-----+-----+
^
|
i
minPrice = 1
maxProfit = 5
Since i has exceeds the array bounds,
the loop will terminate here. The answer
is in maxProfit variable.
Code:
#include <iostream>
#include <vector>
#include <algorithm> // for max, min
using namespace std;
int maxProfit(vector<int>& prices) {
if (prices.empty()) return 0;
int minPrice = prices[0]; // Initially set to the first day's price
int maxProfit = 0; // Initially, no profit is made
for (int i = 1; i < prices.size(); i++) {
// Update the minimum price if a lower price is found
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
// Calculate profit by selling on day i
int profit = prices[i] - minPrice;
// Update maxProfit if this profit is greater
maxProfit = max(maxProfit, profit);
}
}
return maxProfit;
}
int main() {
vector<int> prices = {7, 1, 5, 3, 6, 4};
cout << "Maximum Profit: " << maxProfit(prices) << endl;
return 0;
}
Complexity Analysis:
- Time Complexity:
O(n)
- Space Complexity:
O(1)