121. Best Time to Buy and Sell Stock
Question:
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.
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Source code
Version 1
Idea:
It is a brute force algorithm. Each elements as buying day (prices[i]
)compare the profit with other selling day (prices[j]
, i < j), so we can get the maximum profit, however, the strategy is very inefficient. (Time Limit Exceeded)
Time complexity: O(n2)
Space complexity: O(1)
1 | class Solution { |
Version 2
Idea:
It can use only one loop to implement the algorithm.
minPrice
: It want to get the lowest price up to i-th day.
maxProfit
: It want to get the max profit up to i-th day.
max(maxProfit, prices[i] - minPrice)
: It means that the minimum price subtracted from the price of selling day(prices[i]
) and choose the large profit.
Time complexity: O(n)
Space complexity: O(1)
1 | class Solution { |