Sliding Window: Best Time to Buy and Sell Stock - Leetcode 121 - Python

preview_player
Показать описание


0:00 - Read the problem
0:52 - Drawing solution
5:40 - Coding solution

Leetcode 121
coding interview question

#python #leetcode #neetcode

Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
Рекомендации по теме
Комментарии
Автор

Bro, I just found your channel as I’m preparing for interviews and I cannot say how much your videos are helping me. Thanks for taking the time to do all of them. Truly.

kwaminaessuahmensah
Автор

I always get so close to solving these problems. I have the right idea, but my implementation is never quite there. It is frustrating, but your videos help improve my thinking. Thank you!

dylanskinner
Автор

Best interview prep channel I've found. Really appreciate how succinct you are in explaining things, while also still covering the necessary concepts.

gslette
Автор

Q - Is it just me or are we missing something here? Yes you can move your left pointer all the way to the right but that assumes that later in your array you will have > left pointer or you have have a delta between your left and right pointer greater than any delta which may have existed previously, however, just because you've reached a new all time low doesn't mean that there is a differential greater later in the array. Just my thoughts.
Ans - No, actually i thought the same but the code returns maxprofit not final l and r
let l=[2, 8, 1, 3]
final l and r is 1, 3 the profit is 2 (but will not be returned)
then it is compared with maxprofit which is 8-2=6, since it is less maxprofit is not updated
output will be 6

kirtan
Автор

The other way without the sliding window technique is :
1. Iterate through the prices array.
2. In each iteration keep track of the minimum element seen so far and check for the maximum difference between the currentElement and the minimum element find so far.

For the input from the first Example [7, 1, 5, 3, 6, 4]. The found minimum will be 1 at index 1 and the biggest difference found will be when you are at index 4 with value 6 this will give you the answer 6 - 1 = 5.

This solution is intuitive and easy to implement:

Here is an implementation in a Java code.

class Solution {
public int maxProfit(int[] prices) {
int result = 0, minNum = Integer.MAX_VALUE;

for (int i = 0; i < prices.length; i++) {
minNum = Math.min(minNum, prices[i]);
result = Math.max(result, prices[i] - minNum);
}

return result;
}
}

Btw later try "Best Time to Buy and Sell Stock II" you can go Greedy there again without sliding window technique.

BorisBorovski-mvfl
Автор

This dude solved the problem in O(n) time with two pointer approach and everyone in the leetcode discussion section were complaining that this problem is supposed to medium level, we've to use dp, bad test cases etc etc

erenyeager
Автор

Alternate view :: for(int i = 1; i < n; i++), if we want to sell at i'th position. what we want is to buy at minimum value from previous i - 1. keep a minimum till here.

infiniteloop
Автор

This code worked for me.

class Solution(object):
def maxProfit(self, prices):
lp, rp = 0, 1
max_profit = 0
while rp < len(prices):
if prices[rp] > prices[lp]:
profit = prices[rp] - prices[lp]
max_profit = max(max_profit, profit)
else:
lp = rp
rp=rp+1

return max_profit

Leetcode accepted this, but not the one in the video. The one in the video was giving wrong answer for prices = [1, 2, 4, 2, 5, 7, 2, 4, 9, 0, 9]

Output: 8
Expected: 9

o_o
Автор

*AAAAH* this is *SO MUCH CLEARER* than the dang solution tab for this problem on LC! THANK YOU.

codeisawesome
Автор

class Solution:
def maxProfit(self, prices: List[int]) -> int:
l, r = 0, 1
maxp = 0
while(r < len(prices)):
if prices[l] < prices[r]:
profit =prices[r] - prices[l]
maxp= max(maxp, profit)
else:
l = r

r = r + 1
return maxp

it should be l =r

jr_jeet
Автор

Going through your roadmap right now, I must say, going through each problem with you its so much fun, in fact I don't have time to prepare my resume, portfolio, project etc...omg its like a drug. I keep telling myself I need to start working on other things, but every morning i ended up on your roadmap, working on the next question, oh god I need help.

kuoyulu
Автор

If anyone's confused, I thought of this as:

We're trying to find maxima and minima across the list.

For this, we can only make one comparison: if right (high) is greater than left (low)? Yes? Calculate the profit. Right (high) is smaller than left (low)? That means it's even smaller than what we thought was the minimum, thus it is the new minimum. We have already calculated what the profit was for the elements between these two. So we freely make l = r. We then increase the right pointer in either of the cases and traverse

nachiket
Автор

Is it just me or are we missing something here? Yes you can move your left pointer all the way to the right but that assumes that later in your array you will have > left pointer or you have have a delta between your left and right pointer greater than any delta which may have existed previously, however, just because you've reached a new all time low doesn't mean that there is a differential greater later in the array. Just my thoughts.

summer_xo
Автор

This solution is so much more intuitive and easy to understand the kadane algorithim solution lc provided. Love to see it!

avipatel
Автор

Instead of incrementing left by 1, we can set it to right index. As all the prices between left and right are anyway greater than price at right.

bikaskatwal
Автор

thanks for sharing, I just realized how confusing my solution was, even myself were troubling to understand it and even smallest problem made me rethink whole solution again

AminABbasi
Автор

Is this sliding window or two pointers? I thought for sliding window there needs to be a window size? not sure what the difference between the two is now. Would appreciate an explanation :)

samuelcarrasco
Автор

I made the same error in my code, was freaking out that I couldn't solve an "easy" but your explanation for the bug helped! Thank you :)

rooroo-
Автор

I think the case where the new lowest low occurs that is not followed by a higher high or a lower high with greater distance than the previous max.

niklaslehner
Автор

Was having that same doubt regarding the bug you found at the end of the video. Glad to have it cleared up.

lox_