DEV Community

Cover image for Day 39 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 39 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/buy-stock-with-cooldown/1

Stock Buy and Sell with Cooldown

Difficulty: Medium Accuracy: 51.71%

Given an array arr[], where the ith element of arr[] represents the price of a stock on the ith day (all prices are non-negative integers). Find the maximum profit you can make by buying and selling stocks such that after selling a stock, you cannot buy again on the next day (i.e., there is a one-day cooldown).

Examples:
Input: arr[] = [0, 2, 1, 2, 3]
Output: 3
Explanation: You first buy on day 1, sell on day 2 then cool down, then buy on day 4, and sell on day 5. The total profit earned is (2-0) + (3-2) = 3, which is the maximum achievable profit.
Input: arr[] = [3, 1, 6, 1, 2, 4]
Output: 7
Explanation: You first buy on day 2 and sell on day 3 then cool down, then again you buy on day 5 and then sell on day 6. Clearly, the total profit earned is (6-1) + (4-2) = 7, which is the maximum achievable profit.

Constraint:
1 ≀ arr.size() ≀ 105
1 ≀ arr[i] ≀ 104

Solution:
class Solution:
def maxProfit(self, arr):
if not arr:
return 0
n = len(arr)
hold, sold, rest = -arr[0], 0, 0
for i in range(1, n):
prev_hold, prev_sold, prev_rest = hold, sold, rest
hold = max(prev_hold, prev_rest - arr[i])
sold = prev_hold + arr[i]
rest = max(prev_rest, prev_sold)
return max(sold, rest)

Top comments (0)