Maximizing Score in Grid with Constraints

🚀 LeetCode Day Problem Solving 🚀 Day-64 📌 Problem: You are given an m × n grid with values {0,1,2} and an integer k 🎯 Start from (0,0) → reach (m-1,n-1) ✔ Only move right or down 💰 Cell Contribution: ValueScoreCost0+001+112+21🎯 Goal: ✔ Maximize score ✔ Total cost ≤ k ❌ If not possible → return -1 🧠 Example: Input: grid = [[0,1],[2,0]], k = 1 ✅ Output: 2 💡 Key Insight: ✔ This is DP + Constraint (Knapsack-style) problem 👉 At each cell: We track best score for each possible cost ⚡ State Definition: 👉 dp[i][j][c] = max score reaching (i,j) with cost c ⚡ Transition: From: Top (i-1, j) Left (i, j-1) Add current cell’s: ✔ score ✔ cost 🔥 Optimization Idea: ✔ Instead of full 3D DP → use rolling / pruning ✔ Keep only valid states where cost ≤ k ⚡ Final Steps: 1️⃣ Initialize DP 2️⃣ Traverse grid 3️⃣ Update states from top & left 4️⃣ Track maximum score at (m-1,n-1) with cost ≤ k 📊 Complexity Analysis: ⏱ Time Complexity: O(m * n * k) 📦 Space Complexity: O(m * n * k) (can optimize) 🧠 What I Learned: ✔ Grid DP with constraints ✔ Combining path + cost optimization ✔ Similar to Knapsack + Matrix traversal ✅ Day 64 Completed 🚀 Improving in DP + Optimization + Grid Problems 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories