Max Dot Product of Two Subsequences with DP and Recursion

✏️ DSA Diary Day 14/100 📊➗: Solving LeetCode’s “Maximum Dot Product of Two Subsequences” 🚀✨ Today I worked on a Dynamic Programming + Recursion + Optimization problem on LeetCode 🔥👇 👉 Maximum Dot Product of Two Subsequences This problem is a great example of how DP helps handle complex choices efficiently 🧠💡 🔹 My Approach 🛠️🧠 I used Recursion + Memoization (Top-Down DP) 🔁👇 🔸 Step 1: Define DP State 📌 dp(i, j) = Maximum dot product using elements from nums1[i…] elements from nums2[j…] 🔸 Step 2: Choices at Each Step 🔍 At every (i, j) position, we have 4 options: 1️⃣ Take both elements & continue nums1[i] * nums2[j] + dp(i+1, j+1) 2️⃣ Take both & stop here nums1[i] * nums2[j] 3️⃣ Skip nums1[i] dp(i+1, j) 4️⃣ Skip nums2[j] dp(i, j+1) We take the maximum of all these options 🔝✨ 🔸 Step 3: Memoization 🧠 To avoid recomputation, I used a 2D memo array This reduces time complexity from exponential → O(n*m) 🚀 🔸 Why NEG_INF? ⚠️ To ensure at least one pair is selected, I returned a very small value when indices go out of bounds. 🔹 Key Learnings 📚✨ ✅ DP is perfect for subsequence + optimization problems ✅ Always consider all possible choices ✅ Memoization saves massive computation time ✅ Handling negative values carefully is crucial ✅ Clean recursion = clear logic 🧠💯 🔥 This problem felt like a perfect mix of: 📊 Arrays + 🔁 Recursion + 🧠 DP + 📈 Optimization #LeetCode 🚀 #Java#DSA 🧠 #DynamicProgramming 📊 #ProblemSolving 💡 #CodingChallenge 💻 #100DaysOfCode 🔥 #DSADiaryByRethanya#Recursion 🔁 #Memoization 🧩 #LearnInPublic 📢 #TechJourney 🚀

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories