You are given an array
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
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.
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
1 <= prices.length <= 105 0 <= prices[i] <= 104
Contents
Solution 1 - Using sliding window technique, find the maximum profit window
In this approach, we are going to apply sliding window technique, using two pointers
Implementation steps:
-
First, we will create three variables
left ,right that we will use to adjust the window, andmaxProfit to track the result. Initializeleft=0 andright=1 , that is the beginning window size. -
Next, run a
while loop untilright pointer reaches end of array, and check:-
If left value is less than right value: Check the current profit using
profit = prices[right] - prices[left] , and update themaxProfit - If left value is great than or equal to right value: update the left pointer to right value, since we have already checked current window and next minimum value is at right pointer.
-
Always move
right pointer by 1.
-
If left value is less than right value: Check the current profit using
-
Finally, return
maxProfit .
-
Consider the example with
prices = [7,1,5,3,6,4] . -
Initially,
left = 0 ,right =1 andmaxProfit = 0 . -
In the first step,
prices[left] is greater thanprices[right] , so there is no profit can be made, so updateleft = right = 1 andright = 2 . -
In the second step,
prices[left] is less thanprices[right] , so check the profitprofit = 5 -1 = 4 , update themaxProfit = 4 , increment right pointerright = 3 . -
In the third step,
prices[left] is less thanprices[right] , so check the profitprofit = 3 -1 = 2 , since this profit is less than currentmaxProfit , we will not update it, then increment right pointerright = 4 . -
In the fourth step,
prices[left] is less thanprices[right] , so check the profitprofit = 6 -1 = 5 , since this is higher than current maximum profit, update themaxProfit = 5 , increment right pointerright = 5 . -
In the fifth step,
prices[left] is less thanprices[right] , so check the profitprofit = 4 -1 = 3 , since this profit is less than currentmaxProfit , we will not update it, then increment right pointerright = 6 . -
Since the
right pointer reached end of array, we will exit the loop, and returnmaxProfit found, which is 5.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at