🚀 Daily DSA Practice – Day 57 | Dynamic Programming – Best Time to Buy and Sell Stock (Java) Continuing my DSA journey, today I worked on a classic problem that focuses on maximizing profit from stock prices using a single transaction. 📌 Problem Solved (LeetCode): 121. Best Time to Buy and Sell Stock (Easy) 🎯 Concept: Dynamic Programming / Greedy Optimization 🧠 Problem Idea: Given an array where each element represents the stock price on a given day, determine the maximum profit that can be achieved by buying once and selling once. The key idea is to keep track of: Minimum price seen so far Maximum profit achievable Logic minPrice = min(minPrice, price) profit = max(profit, price - minPrice) 🔍 What I Practiced: ✔ Tracking minimum value while traversing array ✔ Calculating maximum profit efficiently in O(n) ✔ Strengthening greedy + DP optimization thinking ✔ Understanding the foundation of stock trading DP problems This problem is the starting point for more complex stock DP problems like multiple transactions, cooldown periods, and transaction fees. #DSA #LeetCode #DynamicProgramming #Java #ProblemSolving #InterviewPreparation #Consistency #StockProblems
Maximizing Stock Profit with Dynamic Programming in Java
More Relevant Posts
-
🚀 Daily DSA Practice – Day 58 | Dynamic Programming – Best Time to Buy and Sell Stock II (Java) Continuing my DSA journey, today I solved an extension of the stock trading problem where multiple transactions are allowed. 📌 Problem Solved (LeetCode): 122. Best Time to Buy and Sell Stock II (Medium) 🎯 Concept: Greedy + Dynamic Programming 🧠 Problem Idea: Unlike the previous stock problem where only one transaction was allowed, here we can perform multiple buy-sell transactions. The key idea is to capture every profitable price difference between consecutive days. Logic if (prices[i] > prices[i-1]) profit += prices[i] - prices[i-1]; This means we buy at the previous day and sell today whenever there is profit. 🔍 What I Practiced: ✔ Understanding multiple transaction stock problems ✔ Applying greedy optimization techniques ✔ Improving array traversal efficiency ✔ Strengthening the foundation for advanced stock DP problems This problem is an important step toward more complex stock trading problems such as: • Stock with Cooldown • Stock with Transaction Fee • Stock with Limited Transactions #DSA #LeetCode #DynamicProgramming #Java #ProblemSolving #InterviewPreparation #Consistency #StockProblems
To view or add a comment, sign in
-
🚀 Daily DSA Practice – Day 59 | Dynamic Programming – Best Time to Buy and Sell Stock with Cooldown (Java) Continuing my DSA journey, today I solved a more advanced variation of the stock trading problem where an additional constraint is introduced. 📌 Problem Solved (LeetCode): 309. Best Time to Buy and Sell Stock with Cooldown (Medium) 🎯 Concept: Dynamic Programming with State Transitions 🧠 Problem Idea: You can buy and sell stocks multiple times, but after selling a stock, you must wait one day (cooldown) before buying again. To solve this, we track three possible states: • Buy State → Maximum profit when holding a stock • Sell State → Profit after selling the stock • Cooldown State → Rest period after selling DP State Idea buy[i] = max(buy[i-1], cooldown[i-1] - price[i]) sell[i] = buy[i-1] + price[i] cooldown[i] = max(cooldown[i-1], sell[i-1]) 🔍 What I Practiced: ✔ Understanding state-based dynamic programming ✔ Managing multiple DP states simultaneously ✔ Handling cooldown constraints in trading problems ✔ Strengthening logic for complex transition problems This problem helped me understand how DP can model real-world scenarios with multiple decision states. #DSA #LeetCode #DynamicProgramming #Java #ProblemSolving #InterviewPreparation #Consistency #StockProblems
To view or add a comment, sign in
-
Day 94/100 – LeetCode Challenge ✅ Problem: #139 Word Break Difficulty: Medium Language: Java Approach: Dynamic Programming with Max Length Optimization Time Complexity: O(n × m × k) where n = string length, m = max word length, k = avg word length comparison Space Complexity: O(n) Key Insight: dp[i] = true if substring s[0:i) can be segmented into dictionary words. Check all possible word endings ending at position i. Optimize by limiting check to maximum word length in dictionary. Solution Brief: Initialized dp[0] = true (empty string can be segmented). Found maximum word length in dictionary for pruning. For each position i, checked substrings ending at i with length ≤ max_len. If dp[j] is true and substring s[j:i) is in dictionary, set dp[i] = true. Return dp[n]. #LeetCode #Day94 #100DaysOfCode #DynamicProgramming #Java #Algorithm #CodingChallenge #ProblemSolving #WordBreak #MediumProblem #String #DP #Optimization #DSA
To view or add a comment, sign in
-
-
🚀 Daily DSA Practice – Day 62 | Dynamic Programming – Coin Change II (Java) Continuing my Dynamic Programming journey, today I solved a problem focused on counting combinations instead of minimizing values. 📌 Problem Solved (LeetCode): 518. Coin Change II (Medium) 🎯 Concept: Unbounded Knapsack (Count of Ways) 🧠 Problem Idea: Given an amount and coin denominations, find the number of combinations that make up that amount. Unlike Coin Change I, where we minimize coins, here we count total ways. DP Relation dp[j] = dp[j] + dp[j - coin] 🔍 What I Practiced: ✔ Difference between Minimization DP vs Counting DP ✔ Applying Unbounded Knapsack pattern ✔ Using 1D DP optimization ✔ Understanding order-independent combinations This problem helped me clearly understand how DP problems can change significantly based on whether we count ways or optimize values. #DSA #LeetCode #DynamicProgramming #Java #Knapsack #ProblemSolving #InterviewPreparation #Consistency
To view or add a comment, sign in
-
Most developers get this wrong. Do you? 🛑 Early in my Java journey, I thought inheritance was a feature to use freely. The more you extended, the more reusable the code, right? Wrong. Uncontrolled inheritance creates hierarchies nobody can reason about. And Java had no clean answer for it — until sealed classes. ━━━━━━━━━━━━━━━━━━━━━━━━━ Sealed Classes, introduced in Java 17, let you define exactly which classes are permitted to extend yours. No surprises. No rogue subclasses. Just clean, intentional design. public sealed class Shape permits Circle, Rectangle, Triangle {} Each permitted subclass must be one of: → final — no further extension → sealed — further restricted with its own permits → non-sealed — open again by choice And the bonus? Exhaustive pattern matching with switch. The compiler knows every possible subtype. You get compile-time safety for free. ━━━━━━━━━━━━━━━━━━━━━━━━━ I’ve written a full breakdown — how sealed classes work, the rules, and real use cases. Read it here 👇 https://lnkd.in/gsN6Dp7j Have you used sealed classes in your projects? I’d love to hear how! #Java #Java17 #Coding #SoftwareDevelopment #TechCommunity #LearningInPublic #SealedClasses #BackendDevelopment #SoftwareEngineering #CleanCode #OOP
To view or add a comment, sign in
-
-
Why I still value my early C projects. 🛠️ High-level frameworks like Java Collections may be fast, efficient and powerful, but understanding the foundations is what makes a developer truly versatile. Back in 2022-23, I spent weeks building out core DSA models: Stacks, Queues, Graphs, and Dictionaries - using nothing but C. I decided to polish the README and make this personal archive a public repo. What’s inside: 🔹 Modular C logic (Models, Headers, and Runners). 🔹 Manual implementation of BST, Stack, Queue & Graph. 🔹 A straightforward look at memory and structure. It’s not over-engineered or complex; it’s just honest, foundational logic. If you’re practicing for interviews or just want to see how these structures look without the abstraction, feel free to explore and share your suggestions! Repo: https://lnkd.in/d9uspV6Z #Programming #ComputerScience #DSA #C
To view or add a comment, sign in
-
Why Spring Is Moving Back Toward Simplicity Reactive programming became popular because: - Threads were expensive - Blocking didn’t scale That led to code like this: Mono<User> user = service.getUser() .flatMap(this::validate) .flatMap(this::enrich); Powerful — but hard to: - Read - Debug - Maintain Virtual threads allow this again: User user = service.getUser(); validate(user); enrich(user); Same scalability. Much clearer flow. 💡 Takeaway: Spring and Java are converging toward readability. #Java #SpringBoot #BackendEngineering #Java25
To view or add a comment, sign in
-
🚀 Daily DSA Practice – Day 60 | Dynamic Programming – Longest Palindromic Subsequence (Java) Today marks Day 60 of my Daily DSA Practice, and I solved a classic string dynamic programming problem that strengthens understanding of subsequence-based DP patterns. 📌 Problem Solved (LeetCode): 516. Longest Palindromic Subsequence (Medium) 🎯 Concept: String DP (2D DP Table) 🧠 Problem Idea: Given a string, find the length of the longest subsequence that forms a palindrome. Unlike substring problems, subsequence characters do not need to be contiguous. DP Relation If s[i] == s[j] dp[i][j] = 2 + dp[i+1][j-1] Else dp[i][j] = max(dp[i+1][j], dp[i][j-1]) 🔍 What I Practiced: ✔ Understanding subsequence vs substring problems ✔ Building a 2D DP table for string comparison ✔ Solving problems with overlapping subproblems ✔ Improving string DP pattern recognition This problem is closely related to Longest Common Subsequence (LCS) and helps strengthen the foundation for many advanced string DP problems. #DSA #LeetCode #DynamicProgramming #Java #StringDP #ProblemSolving #InterviewPreparation #Consistency
To view or add a comment, sign in
-
🚀 Back with another update from my Java + DSA journey! Staying consistent and focusing on problem-solving mindset over memorizing solutions 💪 Today I worked on building logic step-by-step instead of jumping to code: • Max & Min of 3 Numbers (Using Methods) Created separate functions to find maximum and minimum Broke the problem into smaller comparisons Handled edge cases using >= and <= • Method Design & Parameters Learned how values flow from main() to methods Built clarity on pass by value and parameter usage Understood how methods act as reusable logic blocks • Avoiding Unnecessary Variables Optimized logic by reusing variables instead of creating extra ones Focused on writing cleaner and more efficient methods • Understanding Problem Statements (GFG) Realized that expected output matters more than function name Solved a tricky problem by identifying the real requirement: 👉 Print EVEN number first, then ODD using a function 💡 Key takeaway: Logic > Syntax Well-designed functions make logic clearer and code reusable. Small steps, stronger thinking 🧠🔥 Let’s keep improving every day 🚀 #Day3 #Java #DSA #ProblemSolving #Functions #LearningInPublic #Consistency #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 2 of My Java Full Stack Journey Today I focused on understanding how programs make decisions using conditional statements. 📌 What I learned: 🔹 If-Else Statements Used to control the flow of execution based on conditions 🔹 Types I Practiced: • if • if-else • else-if ladder 🔹 Comparison Operators Used: • == (equal to) • != (not equal to) • > (greater than) • < (less than) • >= (greater than or equal to) • <= (less than or equal to) 🔹 Input / Output Functions • printf() → used to display output • scanf() → used to take input 🔹 Comments • // single-line comment • /* multi-line comment */ 🔹 What I Practiced: Taking user input and applying conditions Understanding how program flow changes step-by-step. Applying concepts in real programs and improving my logic step by step 🚀 #Learninginpublic #javafullstackdevloper #CProgramming #ProblemSolving #Consistency
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development