Here's the Leetcode 122 solution using TypeScript.
Leetcode 122 - Best Time to Buy and Sell Stock II
You are given an integer array prices where prices[i]
is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Approach
Your goal is to find the maximum profit that can be obtained by multiple buy-and-sell transactions on a given stock.
You can use a one-pass algorithm with two pointers, l
and r
, to track the buying and selling days.
Initialize l
and r
to the first and second days, respectively.
Then iterate through the array using a while loop.
In each iteration, check if the price on day l
is less than the price on day r
.
If true, then calculate the profit by subtracting the buying price (prices[l]
) from the selling price (prices[r]
).
The calculated profit is added to the total profit (max
), and the l
pointer is moved to the current selling day (r
).
If the buying price is not less than the selling price, it means a better buying opportunity is found, so the l
pointer is moved to the current selling day (r
) without adding any profit.
This ensures that your algorithm considers multiple transactions for optimal profit.
The final result is the maximum profit obtained by multiple buy-and-sell transactions on the stock.
Code Implementation
function maxProfit(prices: number[]): number {
let l = 0,
r = 1,
max = 0
while (r < prices.length) {
if (prices[l] < prices[r]) {
const profit = prices[r] - prices[l]
max += profit
l++
} else l = r
r++
}
return max
}
Time Complexity
Time complexity is O(n)
, where n
is the length of the input array prices. The algorithm iterates through the array once, and each iteration involves constant-time operations.
Space Complexity
Space complexity is O(1)
or constant. The algorithm uses only a constant amount of extra space for variables.
It doesn't require additional memory that grows with the size of the input array.
Top comments (0)