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
.
OR
Given an array of stock prices, where the increasing indexes of the array signify the increase in time. Return a good time to buy and sell such that profit is maximized. You are allowed to transact only once.
OR
Given an array
A[]
, write an algorithm to find Maximum difference between two elements where larger element appears after the smaller element or in other words findA[i]
andA[j]
such thatA[j]-A[i]
is maximum wherej > i
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Video explanation
Here is the video explaining below few methods in detail. Please check it out:
Method 1: Brute Force
This problem can be easily solved using two nested loops. Take each element at a time and compare it with all the other elements and keep the track of the maximum difference elements where larger element appears after the smaller element.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, because we use two nested loops to check every pair of buying and selling days. - 🧺 Space complexity:
O(1)
as no additional data structures are used.
Method 2 - Greedy
The optimal solution leverages the idea of keeping track of the minimum price encountered so far and calculating the maximum profit along the way. This avoids the need to compare every pair of days explicitly, making the algorithm much more efficient.
Approach
- Initialise Variables:
min_price
to store the minimum stock price encountered so far (initialised to infinity).ans
to store the maximum profit (initialised to0
).
- Iterate Through Prices:
- At each day:
- Check and update
min_price
if the currentprices[i]
is lower than the currentmin_price
. - Calculate the profit for selling on the current day:
profit = prices[i] - min_price
. - Update
ans
if the calculated profit is greater than the currentans
.
- Check and update
- At each day:
- Return the Result:
- After iterating through all days, return the value of
ans
.
- After iterating through all days, return the value of
Code
|
|
|
|
Method 3 - Divide and Conquer
-
We need to find the two elements
A[i]
andA[j]
so thatA[j] – A[i]
is maximum andj > i
-
Divide the input array into 2 parts, left Half and right half.
-
We have divided the problem in 2 parts. Now we can conclude that for answer-
- Both indexes i and j are in the left half of the array.
- Both indexes i and j are in the right half of the array.
- Index i is in left half and index j is in right half of the array.
-
Solve the above 3 sub problems recursively and final answer will the maximum of these 3 sub problems.
This solution is very much similar to Merge sort.
Complexity
Time complexity is O(nlogn).
Code
|
|
Method 4 - Kadane - Tracking Diff with Min Element so Far
In this method, instead of taking difference of the picked element with every other element, we take the difference with the minimum element found so far. So we need to keep track of 2 things:
- Maximum difference found so far (max_diff).
- Minimum number visited so far (min_element)
Code
|
|
|
|
|
|
Complexity
Time Complexity: O(n), Auxiliary Space: O(1)
Method 5 - Kadane - Tracking Diff with Max Element so Far
Previous solution was on min_so_far
, now we have max_so_far
.
- Traverse the array from right to left.
- Maintain 2 variables – maxDifference (this will be our final answer), and max_so_far(maximum element we encounter while traversing the array)
- During iteration, every element has 2 choices
- Either current element is the maximum element among elements which are iterated, if yes then max_so_far = current element.
- OR current element is less than the max_so_far. If yes then update the maxDifference = max_so_far – current element.
- Once the iteration is done, return maxDifference.
Complexity
Time complexity: O(n), Space complexity: O(1)
Code
|
|
Complexity
Time Complexity: O(n), Auxiliary Space: O(1)
Method 6 - Dynamic Programming - Max Sum Subarray
First find the difference between the adjacent elements of the array and store all differences in an auxiliary array diff[] of size n-1. Now this problems turns into finding the maximum sum subarray of this difference array.
Code
|
|
Method 7 - 2 Pointer Approach
Code
|
|
Complexity
Time Complexity: O(n), Auxiliary Space: O(1)