🗓 Day 96 / 100 – #100DaysOfLeetCode 🔥 📌 Problem 3836: Maximum Score Using Exactly K Pairs Difficulty: Hard Today’s problem was a solid dynamic programming + optimization challenge. The task was to select exactly k pairs of indices from two arrays while preserving order, such that the sum of products of the chosen pairs is maximized. 🧠 Key Insight: This problem is essentially about choosing pairs in order, where each choice affects future possibilities. Brute force is impossible due to constraints — the solution requires DP with careful state transitions. 🧠 My Approach: Used Dynamic Programming, where the state represents: how many elements have been considered from both arrays how many pairs have already been formed At each step, had two choices: skip an element form a pair and add its product to the score Ensured: exactly k pairs are chosen index order is preserved in both arrays Tracked the maximum achievable score across all valid transitions. This structured DP approach ensures correctness even with large inputs. ⏱ Complexity: Time: Optimized DP (within constraints) Space: DP-based state storage 💡 Key Learning: ✔ transforming pair-selection problems into DP ✔ managing multi-dimensional states cleanly ✔ why “exactly k choices” often signals a DP solution ✔ Hard problems are all about modeling, not brute force 💪 Day 96 complete — only 4 days left to finish the 100-day journey! 🚀 #100DaysOfLeetCode #LeetCodeChallenge #ProblemSolving #DynamicProgramming #HardProblems #Optimization #Algorithms #DSA #CompetitiveProgramming #CodingJourney #LearningInPublic #KeepLearning
Maximizing Score with Dynamic Programming and Optimization
More Relevant Posts
-
Day 53/365 – Perfect Squares Given an integer n, return the minimum number of perfect squares that sum to n. Example: 12 → 4 + 4 + 4 → Output = 3 13 → 4 + 9 → Output = 2 💡 The Idea: Dynamic Programming Let: dp[i] = minimum number of perfect squares that sum to i Worst case? Use 1² i times → dp[i] = i Then improve it by checking: For every square j² ≤ i 👉 dp[i] = min(dp[i], dp[i - j²] + 1) We build the solution bottom-up. 🧠 Why this works Each number builds upon smaller results. It’s like asking: “If I remove one perfect square, what’s the best answer for the remaining value?” ⏱️ Complexity Time: O(n √n) Space: O(n) ✨ Big takeaway: When a problem asks for minimum steps / minimum count, think Dynamic Programming. Break it down. Build it up. #Day53 #365DaysOfCode #LeetCode #DynamicProgramming #DP #Algorithms #DSA #InterviewPrep #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Day 20 of #30DaysOfAdvancedDSA | Today was all about Medium-level Recursion — building a strong base for mastering Dynamic Programming later. Instead of jumping directly into DP, I focused on understanding recursion deeply — especially how decisions, branching, and backtracking actually work. Problems I solved (6 Mediums): 1️⃣ Combination Sum Learned how to: Pick / Not Pick pattern Stay on the same index to allow reuse Think in terms of target reduction 2️⃣ Combination Sum II Learned how to: Handle duplicates carefully Use sorting + skip same elements Understand why the i > index check matters 3️⃣ Subsets Learned how to: Build a pure recursion tree Apply Include / Exclude pattern Understand the foundation of power set logic 4️⃣ Subsets II Learned how to: Generate subsets with duplicates Control recursion branches Prevent duplicate subsets 5️⃣ Combination Sum III Learned how to: Work with fixed-size combinations Control recursion depth Manage both count and sum constraints 6️⃣ Letter Combinations of a Phone Number Learned how to: Apply recursion over strings Map digits → characters Build combinations step by step While dry running these problems, it honestly feels like time moves in double speed 😅 DP next 🚀 #DSA #Recursion #Backtracking #Consistency #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Hello, world!! During my recent project (php-json library), I had frequent scenarios where I had to choose between using regular loops or recursion to resolve each properties of a class and any embedded object properties. Ideally, the right way is to use the recursion as it is best suited for nested properties while loops can only go over a layer. So I took this option and utilised PHPs Reflection class to get the properties and recursively resolve them properly almost the same way a DI Container would. In another scenario, the loops will be the better choice as it has less space efficiency and doesn't stand a risk off stack overflow, perfect for huge sized data. In a nutshell, using recursion (especially with a logic to prevent infinite recursion) provides a logical and elegant code but isn't suited for working with large data, while loops work with large but simple one-layered data sets. Loops can also work with multiple layers, but will however, introduce badly nested for-loops which will eventually lead to code smells and bugs. Thank you for your time and have a productive week!! #Programming #CleanCode #SoftwareEngineering #DataStructures #Recursion
To view or add a comment, sign in
-
-
🌳Problem: Balanced Binary Tree 🟢Difficulty: Easy ⚖️Goal: Check if a binary tree is height-balanced (for every node, height difference ≤ 1). 💡 Approach (Optimized DFS + Early Exit) Instead of calculating height separately for every node (which can lead to repeated computations), I used a single DFS traversal where: The function returns the height if the subtree is balanced Returns -1 immediately if the subtree is unbalanced This allows early stopping, saving unnecessary recursion. 🔥 Key Insight Many leaderboard solutions compute both left and right subtree heights first, then check if either is -1. That may look cleaner but that may cause redundant recursion, because even if the left subtree is already unbalanced, the right subtree still gets computed. In my solution, I check left first: if left is -1 → stop instantly else compute right This avoids extra DFS calls and improves efficiency. ⏱️ Complexity ✅ Time: O(n) (each node visited once) ✅ Space: O(h) (recursion stack) 🧠 Takeaway Sometimes writing code in fewer lines looks clean, but adding early exits can make it much more efficient in real execution. #leetcode #dsa #binarytree #recursion #dfs #cplusplus #programming #coding #LearningInPublic #softwareengineering #competitiveprogramming
To view or add a comment, sign in
-
-
🚀Back to the Grind Headline: Rebuilding the Habit — From Sliding Windows to Recursion Trees It feels good to be back on the LeetCode rhythm after a short break. Today was all about sharpening my skills in String & Bit Manipulation, with a deep dive into Recursive Backtracking: ✅ Count Binary Substrings (Grouping logic) ✅ Longest Substring Without Repeating Characters (Sliding Window) ✅ Alternating Bits (Bit properties) ✅ Subsets / Power Set (Recursive "Include/Exclude" pattern) 💡 The Big Takeaway Many "hard-looking" problems start to crumble once you identify the underlying pattern. Whether it’s realizing a sliding window can handle dynamic ranges or seeing recursion as a decision tree, the logic is usually there. The real challenge? Boundary handling. Most of my "Wrong Answer" submissions today weren't because of a flawed core strategy, but because of a missed base case or a ±1 error. It's a humble reminder that in software, the details aren't just details; they are the product. Slow progress > no progress 🚀 #LeetCode #DSA #Recursion #ProblemSolving #CodingPractice #KeepLearning #ComputerScience #SoftwareEngineering
To view or add a comment, sign in
-
-
DSA Practice – Day 11 | Difficulty-Balanced Set Solved on LeetCode and GFG, focusing on backtracking, recursion, combinatorics, and dynamic programming: Medium • LC 40 – Combination Sum II — Backtracking, Duplicate Handling • LC 46 – Permutations — Backtracking • LC 78 – Subsets — Backtracking, Bit Manipulation • LC 377 – Combination Sum IV — Dynamic Programming GFG • Rat Maze With Multiple Jumps — Backtracking, Matrix Traversal, Recursion Core topics covered: Backtracking, Recursion, Dynamic Programming, Combinatorics, Matrix Traversal #DSA #LeetCode #GeeksforGeeks #Algorithms #DataStructures #ProblemSolving
To view or add a comment, sign in
-
I’ve just wrapped up a deep dive into the fundamental building blocks of programming: Functions and Conditional Logic. It’s one thing to make a computer run a script; it’s another to teach it how to make decisions. This week was all about: 🔹 Modular Thinking: Breaking down complex problems into reusable functions. 🔹 Conditional Flow: Using if/elif/else structures to guide how a program reacts to different inputs. 🔹 Data Integrity: Ensuring user input is correctly handled and converted (shoutout to float() and int()) before any calculation happens. I also built a Torque Calculator and a Smart Team Router to put these concepts into practice. It’s not just about writing lines of code anymore—it's about building a logical flow that actually solves a problem. Next step: Mastering Loops. The journey to thinking like a programmer continues! 🚀 #Python #Programming #LearningToCode #SoftwareDevelopment #Logic #CodeNewbie
To view or add a comment, sign in
-
Today I built an ATM simulation in Python to practice backend logic and authentication systems. Implemented: 3-attempt PIN security system Transaction handling (withdrawals & balance checks) Clean function-based architecture Each project I build is focused on strengthening problem-solving and system design skills as I grow toward software development mastery. Here is a sample: https://lnkd.in/evPxa-Md
To view or add a comment, sign in
-
Reached 300 LeetCode Problems Instead of focusing only on the count, I’ve been tracking the problem-solving patterns I’ve practiced so far: ✔ Arrays, Strings & Hashing ✔ Two Pointers & Binary Search ✔ Linked List, Stack, Queue & Sorting ✔ Trees / Binary Trees & BSTs ✔ DFS & BFS ✔ Graph Traversal (BFS/DFS) ✔ DSU (Disjoint Set Union) ✔ Shortest Path Algorithms ✔ Topological Sorting ✔ Backtracking & Monotonic Stack ✔ Prefix Sum 📊 Difficulty Breakdown: • Easy: 108 • Medium: 170 • Hard: 22 This approach has helped me build strong fundamentals and recognize patterns during interviews and contests — rather than memorizing solutions. 📈 Current Focus: • Going deeper into Dynamic Programming • Improving contest performance
To view or add a comment, sign in
-
-
Solved another interesting Binary Tree problem today — Diameter of Binary Tree (C++). Focused on optimizing the approach by combining height calculation with diameter tracking in a single DFS traversal, which helped achieve efficient time complexity and clean recursive logic. Always satisfying when a solution passes all test cases with optimal performance. Key takeaways: • Using post-order traversal to compute subtree heights • Maintaining a reference variable to track maximum diameter during recursion • Writing concise and efficient recursive code without redundant calculations Consistent problem-solving is helping me sharpen my understanding of data structures, recursion patterns, and algorithmic thinking. #DataStructures #Algorithms #DSA #BinaryTree #CPP #Programming #CodingJourney #SoftwareDevelopment #ProblemSolving #LeetCode
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