Program to find minimum cost to reach final index with at most k steps in python

Suppose we have a list of numbers nums and another value k. The items at nums[i] represent the costs of landing at index i. We start from index 0 and need to reach the last index of nums. In each step we can jump from position X to any position up to k steps away. We need to minimize the sum of costs to reach the last index.

So, if the input is like nums = [2, 3, 4, 5, 6] and k = 2, then the output will be 12, as we can select the path: 2 + 4 + 6 to get a minimum cost of 12.

Algorithm

To solve this problem, we will follow these steps ?

  • Initialize ans = 0 and an empty min-heap h
  • For each index i from 0 to size of nums:
    • Remove outdated entries from heap (positions more than k steps away)
    • Get minimum cost from valid previous positions
    • Calculate current cost: ans = nums[i] + val
    • Add current position and cost to heap
  • Return the final answer

Example

Let's implement this solution using a min-heap approach ?

from heapq import heappush, heappop

class Solution:
    def solve(self, nums, k):
        ans = 0
        h = []
        
        for i in range(len(nums)):
            val = 0
            # Remove positions that are more than k steps away
            while h:
                val, index = h[0]
                if index >= i - k:
                    break
                else:
                    heappop(h)
            
            # Calculate minimum cost to reach current position
            ans = nums[i] + val
            # Add current position with its cost to heap
            heappush(h, (ans, i))
        
        return ans

# Test the solution
ob = Solution()
nums = [2, 3, 4, 5, 6]
k = 2
print(f"Minimum cost: {ob.solve(nums, k)}")
Minimum cost: 12

How It Works

The algorithm uses a min-heap to efficiently track the minimum cost paths. For the example [2, 3, 4, 5, 6] with k = 2:

  • Index 0: Cost = 2 (starting position)
  • Index 1: Cost = 2 + 3 = 5 (from index 0)
  • Index 2: Cost = min(2 + 4, 5 + 4) = 6 (from index 0)
  • Index 3: Cost = min(5 + 5, 6 + 5) = 10 (from index 1)
  • Index 4: Cost = min(6 + 6, 10 + 6) = 12 (from index 2)

The optimal path is: 0 ? 2 ? 4 with costs 2 + 4 + 6 = 12.

Time Complexity

The time complexity is O(n log n) where n is the length of nums, due to heap operations. The space complexity is O(n) for the heap storage.

Conclusion

This dynamic programming solution with min-heap efficiently finds the minimum cost path by maintaining optimal costs at each step. The heap ensures we always choose the cheapest previous position within k steps.

Updated on: 2026-03-25T13:07:45+05:30

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements