
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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. Here the items at nums[i] represents the costs of landing at index i. If we start from index 0 and end at the last index of nums. In each step we can jump from some position X to any position up to k steps away. We have to minimize the sum of costs to reach last index, so what will be the minimum sum?
So, if the input is like nums = [2, 3, 4, 5, 6] k = 2, then the output will be 12, as we can select 2 + 4 + 6 to get a minimum cost of 12.
To solve this, we will follow these steps −
- ans := 0
- h := an empty heap
- for i in range 0 to size of nums, do
- val := 0
- while h is not empty, do
- [val, index] := h[0]
- if index >= i - k, then
- come out from the loop
- otherwise,
- delete top from the heap h
- ans := nums[i] + val
- insert pair (ans, i) into heap h
- return ans
Let us see the following implementation to get better understanding −
Example
from heapq import heappush, heappop class Solution: def solve(self, nums, k): ans = 0 h = [] for i in range(len(nums)): val = 0 while h: val, index = h[0] if index >= i - k: break else: heappop(h) ans = nums[i] + val heappush(h, (ans, i)) return ans ob = Solution() nums = [2, 3, 4, 5, 6] k = 2 print(ob.solve(nums, k))
Input
[2, 3, 4, 5, 6], 2
Output
12
- Related Articles
- Program to find number of minimum steps to reach last index in Python
- Program to find cost to reach final index of any of given two lists in Python
- Program to find minimum number of buses required to reach final target in python
- Program to find minimum cost to hire k workers in Python
- Program to find minimum cost to paint fences with k different colors in Python
- Program to find minimum steps to reach target position by a chess knight in Python
- Program to find minimum possible integer after at most k adjacent swaps on digits in Python
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- Program to find minimum jumps to reach home in Python
- Program to find sum of rectangle whose sum at most k in Python
- Program to find minimum cost to merge stones in Python
- Find the minimum cost to reach destination using a train
- Program to Find Minimum Jumps Required to Reach a Value with Different Parity in Python
- Program to find to get minimum cost to climb at the top of stairs in Python?
- C++ code to count steps to reach final position by robot

Advertisements