Anas Dew
Posted on December 18, 2022
Hey dev! In case you don't know, I've started #45daysofleetcode and in these 45 days i'll be writing about two problems every day.
The problem, how I solved it and a bit of detailed explanation.
I'm sharing this progress with you so that you too can learn a bit of different perspective and have new solutions so hit like to join this journey.
I've chosen the best list of problems from medium to hard. That made lots of developers crack the interview.
Are you excited?
Today's Problem
Name - Best time to buy and sell stock - 2
Description - 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.
Example
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
My Approach
Initialize two values -> maxProfits and step.
Iterate through the array from 0 to list length-1 and step is for jumping because we cannot buy sell twice a day.
If next day price is higher than today's price then -> next day price - today's price = today profit.
add it to maxProfits, and skip next day and goto another day and so on.
But if next day price is not higher than today's price then do nothing and move on. ref: else condition. step = 1 will do nothing but step = 2 skips a day.
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfits = 0
step = 1
for i in range(0, len(prices)-1, step):
if prices[i+1] > prices[i] :
maxProfits += prices[i+1] - prices[i]
step = 2
else :
step = 1
return maxProfits
Let me know if you've any questions or suggestions!.
If you want full list of solutions, here's the list. Make sure you star the repository.
Follow to join this #45daysofleetcode
Bye!
Posted on December 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.