
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Cost to Reach Final Index of Two Lists in Python
Suppose we have two lists of numbers nums0 and nums1 of the same length and two other values d as distance and c as cost. If we start from index 0 at either nums0 or nums1 and want to end up at the final index of either list. Now, in each round, we can select to switch to the other list for cost of cost. Then we can jump forward at most d distance away where the c cost of landing at an index is the value at that point. So we have to find the minimum total cost possible to complete the task.
So, if the input is like nums0 = [2, 3, 10, 10, 6] nums1 = [10, 10, 4, 5, 100] d = 2 c = 3, then the output will be 18, as we can start from 2, then switch to the second list to 4, again switch back to first list to 6. So cost 2 + 4 + 6 = 12 and switch twice with cost 3 each so total is 18.
To solve this, we will follow these steps −
- switch := a map with key 0 for nums0, and key 1 for nums1
- Define a function search() . This will take idx, nums
- if idx >= size of switch[nums] , then
- return inf
- if idx is same as size of switch[nums] - 1, then
- return switch[nums, -1]
- c := inf
- for i in range 1 to dist + 1, do
- c := minimum of c and switch[nums, idx] + search(idx + i, nums)
- c := minimum of c and switch[nums, idx] + cost + search(idx + i, invert of nums)
- return c
- from the main method do the following −
- return minimum of search(0, 0) and search(0, 1)
Example (Python)
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums0, nums1, dist, cost): switch = {0: nums0, 1: nums1} def search(idx, nums): if idx >= len(switch[nums]): return float("inf") if idx == len(switch[nums]) - 1: return switch[nums][-1] c = float("inf") for i in range(1, dist + 1): c = min(c, switch[nums][idx] + search(idx + i, nums)) c = min(c, switch[nums][idx] + cost + search(idx + i, int(not nums))) return c return min(search(0, 0), search(0, 1)) ob = Solution() nums0 = [2, 3, 10, 10, 6] nums1 = [10, 10, 4, 5, 100] d = 2 c = 3 print(ob.solve(nums0, nums1, d, c))
Input
[2, 3, 10, 10, 6],[10, 10, 4, 5, 100], 2, 3
Output
18