Best time to buy and sell stock to Maximise Profit Leetcode - 121 | Java and C++ | DSAOne Course #14
ฝัง
- เผยแพร่เมื่อ 28 ส.ค. 2024
- Hey guys, In this video, we're going to solve a very famous Leetcode problem known as the Best time to Buy and Sell a stock - part 1.
Practice here: practice.geeks...
🚀 Follow me on:
Instagram: / anuj.kumar.sharma
Linkedin: / sharma-kumar-anuj
Twitter: / realanujbhaiya
╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
╠╗║╚╝║║╠╗║╚╣║║║║║═╣
╚═╩══╩═╩═╩═╩╝╚╩═╩═╝
🥳 Join our Telegram Community:
Telegram channel: t.me/coding_en...
Telegram group: t.me/dsa_one
💸 Visit www.educative.... to avail discount on all courses on Educative!
💸 Use coupon code ANUJBHAIYA on GeeksforGeeks to avail discounts on courses!
📚 Complete DSA Playlist: • DSA-One Course - The C...
Complete Android Development Playlist: • Android Development Tu...
Hashtags:
#anujbhaiya #dsaone #leetcode
Ignore these tags:
best time to buy and sell stock leetcode
best time to buy and sell stock
stock buy and sell
anuj bhaiya
stock buy and sell leetcode
maximum profit by buying and selling a share at most twice
buy and sell stocks leetcode
121. best time to buy and sell stock
stock buy sell to maximize profit
stock buy and sell problem
leetcode 121
stock buy and sell gfg
leetcode
stock span problem
buy and sell stock leetcode
maximum profit
best time to buy stocks
best time to buy and sell stock ii
when to buy and sell stocks
buy and sell stocks
best time to buy stocks leetcode
stock buy and sell problem leetcode
best time to buy and sell stock iii
best time to sell stocks
leetcode best time to buy and sell stock
buy and sell stock
stock buy sell problem
dsa
when buy and sell stock
dsa one
buy and sell stocks for beginners
maximum profit gfg
best time to buy and sell stock i
kadane's algorithm
stock buy sell leetcode
best time to buy and sell stocks
buying and selling stocks
best time to sell stocks leetcode
leetcode problems
maximum profit by buying and selling a share at most k times
best time to buy and sell stock with transaction fee
kadane algorithm
minimize the heights ii
stock maximize
anuj
buy and sell
maximum profit by buying and selling a share atmost twice
rearrange array in alternating positive & negative items with o(1) extra space
best time to buy and sell stock iv
buy sell stocks
dsa full course
dsa using c++
leet code
love babbar
stock buy sell
stock for profit
stock maximize hackerrank
stock profit
stock span
when to sell stocks
a company has a number of products in stock coding question
algorithms
anuj bhaiya dsa
best time to buy and sell stock leetcode python
best time to buy and sell stock python
buying and selling stocks for beginners
count inversion
dsa with java
dynamic programming problems
garry sandhu
get saged
largest sum contiguous subarray
leetcode solutions
maximum product subarray
maximum profit by buying and selling share at most twice
rain water tapping problem
rain water trapping problem
stock buy
tcs buy or sell
trapping rain water problem
two sum leetcode c++ solution
when share buy and sell
121
algorithm
allocate minimum number of pages
amazon online assessment test
amazon salary
anuj bhaiya java
apna college
apni kaksha python
array program in java
best time to buy and sell stock atmost b times
best time to buy and sell stock ii leetcode
best time to buy and sell stock with cooldown
binary tree maximum path sum
buy sell
buy sell stock leetcode
leetcode
leetcode 121
best time to buy and sell stock leetcode
leet code 121
leetcode 121 best time to buy and sell stock
leetcode 121 python
leetcode 121 solution
leetcode 121 tutorial
eric programming leetcode 121
leetcode solutions
buy and sell stocks leetcode
leetcode 2021
121. best time to buy and sell stock leetcode
leet code 121 explained
leetcode best time to buy and sell stock
python leetcode
leetcode stocks
leetcode solution
leetcode problems
I was asked to solve this problem in Walmart interview.
The explanation becomes more easy to understand when its in hindi, Thanks for the solution.:)
bhai shii me lol! English me utna thik nhi lagta
Interviewer ko bhi yahi bolega kya? How do you expect to explain something in english if you can't understand it in english.
method4(int a[]){
int sum=0, maxProfit=0;
for(int i=0; imaxProfit) maxProfit = sum;
if(sum
not working for me
The best thing about your lecture bhaiya is your time complexity(video duration) rest other youtubers take half an hour minimum for same quality.
Please upload videos more frequently for this course.
excellent, teachings and topics and anyone can understand them very easily even though if they don't know the java or c, because he explains the logic in such a way that you can code it it in your preferred language.
Thanks Anuj Bhaiya . Actually I got the logic exact when he told to think how to solve with O(n) and constant space.
i am so happy that god snd me to code at that time where tech is giving a lot of support in my coding journey , from these smart teachers , i can do anything ...
Really feeling the love for DSA by your video.. Thank so much @Anuj Bhaiya
python solution
def buyAndSellStocks(arr):
maximum = max(arr)
minimum = min(arr[:arr.index(maximum)])
return maximum-minimum
l = list(map(int, input().split()))
print(buyAndSellStocks(l))
This one with O(N) time complexity for returning the days . This is in python.
def buyAndSellStocks(arr) :
Max=-1
for i in range (len(arr)):
mini = arr[i]
maxi= max(arr[ i+1:])
Pr= maxi-mini
if Max
Your program fail with this test case
8,1,7 @Siddhant Goyal
The way you articulate it's amazing thanks 😃
Bhaiya knows that we don't like long videos, thus he makes parts 😎😎
Please make a video on rainwater trap
That'll come soon, stay tuned 🙌
@@AnujBhaiya thanks 😀
Great Sir 😎
#TheAnalysers
agar koi solve karne ke baad aaya hai (means code ko optimize karne ke liye)
yaar video dekhne se pehle humne kese solve kiya or koi hmara code dekhega to heart attack aa jayega
fir video dekhne ke baad me 300 line ke code ko 3 line me likhte hai leetcode pe 🤣🤣🤣🤣🤣
Thank You anuj bhaiya.....
DSA-ONE course helps a lot.....
Stay home (if possible)
Stay Safe (must)
Please upload the video frequently and more complex question frequently asked in competitive programming
Seriously your Auxiliary array explanation was awesome !! thank you again ...
Bhaiya I have a request...please make a video on the topic :
Minimum no of jumps to reach end of the array
another approach for super optimised solution.
class Solution {
public:
int maxProfit(vector& prices) {
int n=prices.size();
int max=prices[n-1],ans=0;
for(int i=n-2;i>=0;i--){
max=prices[i]>max?prices[i]:max;
int p=max-prices[i];
if(p>ans){
ans=p;
}
}
return ans;
}
};
your explanations are always outstanding, thank you
Probably this is better code to understand.
int prices[] = {3,5,2,1,6,9,5,6};
int MinPrice = prices[0];
int MaxProfit = 0;
for(int i=0;i
mind- blowing explanation anuj bhaiya love from Andhra Pradesh
from your solution not a single test case is passing in binary search can u pls tell why??? Testcase
prices = [1, 5, 3, 4, 6]
Your result
5
Expected
7
@Anuj Bhaiya
@@DeepakChauhan-mj2wt binary search
Excellent teaching given by you which is in very simplest way... Thank you bhaiyaa...
bro at what time you started coding
@@d.aditya1398 right now
Bhaiya plz second wala bhi video banadena asap if possible u are really doing a great job , thank you so much .
Excellent video👌
Bhaiya one small doubt can Open source Contribution is counted as work experience??
meanwhile....me reading the question partially and thinking of sorting the array and returning the difference of first and last element🤣🤣🤣🤣🤣🤣
Mee too😂
Thank bhaya, just I needing this type of video.
Brute force is also a solution. Bilkul sahi
Bhaiyya isko O(N) TC m aur constant space m ek method se aur solve kr skte na ....ek for loop m phle max element nikal lo aur fir ek doosra loop chala k us index tak min element nikalne ka loop chala do....aur un dono ka difference hi max profit hoga.
bhai sach mein bohot badhiyaa
Sir plz guide me I have 3 years gap after graduation . I want to join a company . I am learning c++ , java , data structures by myself . I am from ece background . What should I do extra like projects , or any specific course so that I can start my career . I have done blunders in my life . I want to support my family . Plz guide me about things that I can do for selection in a company .my friend is in it company I am taking help from him also . Your response is highly appreciated thanks
I thought that another tech channel became a fintech channel
Ye amazing course ke liye bohot bohot shukriya ! I hope ki aap aese he detailed videos banate rahenge ...
Ek question aur ek request tha !
Bhaiya , kab tak ye course khatam hoga ?
Aur,
Kya aap ek hafte mein thoda zyada videos daal payenge please ? ( 3-4 )
Innn
First like
Make a video on ai development 🔥
Thanks for explaining how to start from naive approach to optimized solutions
Bhaiya
Phale yaadi aapan minimum value ka index nikal le then usse index k baad konsi value max hai vo dekh le toh bhi solve easily ho sakta hai
Complexity mein thodi variation hogi shyd
Waise I love your content BhaiYa. All the Best 👍❤️👍
Aagaya aagaya maal aagaya😂
Very well explaination starting from brute force approach.
Anuj Bhaiya hmain sirf profit ni nikalna minsofar bhi btana hai is case main 2 hai but second last element update ho jata hai minsofar = 1
bhaiya you teaching in very lucid language and now i think DSA is not much difficult.
catch yahan yahi hai , if lowest price is at the end of the array then, how anyone can maximise profit ;)
Kya hum is question me esa kar skte h ki phle minimum element aur uska index nikal le phir usse phle ki index tak ke minimum aur maximum nikale fir un dono ka difference nikale vo element a
Fir hum minimum element ke baad vala maximum value nikale fir yeh vali maximum value aur minimum element ka difference b
Fir finally hum a, b ka max output de de
Question O(n) me solve ho skta h
But kya isme koi corner case hoga??
awesome solution, really loved the thought process for each step
Bhaiya please upload videos more frequently for this course. 🥺
Very simple and best learning approach
sorry sir . but i think it will not work on input............
a=[3,2,4,8,9,1,5]
because at last
minsoFar=1
profit=7, but we can't sell old day and sell in future......................
please sir give some clarification.
ek dam clear samajhaya bhaiya aapne:)
great teaching skills..
Thanks Auj Bhaiya !
By what time entire course of DSA be uploaded
Bhaiya please replay me can I be a software engineer without
College degree
Yes you can
bhaiya mtlb gazab bahut mast explain kiya
Best Explaination Ever!!
I thought you discontinued the course.
Thanks!
Is Criptocurrency is safe for investment.
Thank you Bhaiya
Great explanation 👍
For (7,1,5,3,6,4) pr maximum profit 6 aayega with (including space), but when we use 3rd method then the maximum profit = 5??
5 he toh ayega
you are my Guardian angel😇😇
Thanks bhaiya
Please make a video on the problem of Minimum no of Jumps to reach end of an array
Thank you for explaining
Please continue this video series
Bhaiya array ko increasing order sort karke last minus 1st element kyu nhi kr sakte
That would alter the order of prices. And you can only buy first then sell it.
why we not direct sort and do our work ??
For eg if we take array[ ] = 9,8,7,5,6,4
Max profit must be =1
But if we sort it array will be 4,5,6,7,8,9
And Max profit will become 5 which is wrong.
Because we cannot sell stock before buying it.
Thank you Bhaiya 🥳...
love you brother! and thanks much for the clear cut explanation.
beautiful approach
This one with O(N) time complexity for returning the days . This is in python.
def buyAndSellStocks(arr) :
Max=-1
for i in range (len(arr)):
mini = arr[i]
maxi= max(set(arr[ i: ] ))
Pr= maxi-mini
if Max
Thank u very much, It was great video
Thanks for easy explanation
Bhaiyaa can we do it like this? First we find the maximum value in the array and store its index, say 'i'. Next we find the min value present in 0 to (i - 1) index. there are two O(N) operations... overall complexity is O(n) then
it would still need two passes of the array . The given solution is much faster
int Solution::maxProfit(const vector &A) {
if(A.size()==0)
{
return 0;
}
long long int maxPrice=INT_MIN,minPrice=INT_MAX, lowerIdx=0, highIdx=0;
for(long long int i=0; i
Thanks bhaiya for amazing explaination. ❤️❤️
what if there is 0 after 8?
any corner case for that?
Bhaiya this can be further optimised to log(n) time complexity using ordered sets or PBDS in C++ GNU. 🙏 Would be helpful if you make a video on it.
Really? how?
Lol..to construct the data structure itself you would require O(NlogN) time, but you can query in O(logN)
Love u bro 🤗 Big fan of ur teaching 😊❤️
we can also acheive this by max_so_far
class Solution {
public int maxProfit(int[] prices) {
int n=prices.length,profit=0;
int max=0;
for(int i=n-1;i>=0;i--){
max=Math.max(prices[i],max);
profit=Math.max(profit,max-prices[i]);
}
return profit;
}
}
Thank you anuj bhaiya😀
This is what I was thinking😅
Thanks bhaiya it helped a lot
Need videos on algo trading
Hello bhaiya I solved around 40 to 50 questions of arrays in geekforgeeks including hard and medium. But now I was trying to solve the question in leetcode I can't remember the logic. How will I remember till my placement.
Sorry for asking same question but I want ask whether I am learning in right way or not because if I can't remember the logic then what is the use of doing these question.
I see your videos and understand the logic but after some days I have to see the video. So can you tell me how did you overcome this problem in your time.
Make your own notes
In second solution of O(N) space: if the first element of the a[ ] is largest then, In the auxiliary array -> aux[0] will be updated as the max number and will end up giving wrong answer. so we should only update till the second element of a[ ]
How?
But that same max number is getting substrated by aux array so it will give 0 ans in first iteration and that's correct in that case
Thanks sir..♥
Anuj bhaiya you saved Anuj bhaiya, but i am having some issues with a similar problem just with multiple stocks given. Can you help on how this can be adapted for that problem also at most k transactions are allowed.
Bhaiya bacha lo
nice question
Great logic ,
Amazing
Nice explanation. 👍
Bhaiya isme ek ar trick use kar sakte h kya jese if(a[I]
thank you so much bhaiya🤗🤗
Make a video on a.i. development 🔥 road map 🔥
Arrays ko sort kar ke nahi kar sakte kya ??
Great Explanation.
Outstanding explanation !!!
See Anuj Bhaiya Gave me a heart ❤️👇
int maxProfit(vector& prices) {
int temp=prices[0];
int ans=INT_MIN;
for(int i=0;i
How to find and return the indices of best day to buy and best day to sell with max profit?
thank you bhaiya ❤️❣️