Program to find cost to reach final index of any of given two lists in Python

PythonServer Side ProgrammingProgramming

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 −

 Live Demo

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
raja
Published on 12-Dec-2020 14:12:27
Advertisements