Program to find number of operations needed to convert list into non-increasing list in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums. Now let us consider an operation where we take two consecutive values and merge it into one value by taking their sum. We have to find the minimum number of operations required so that the list turns into non−increasing.

So, if the input is like nums = [2, 6, 4, 10, 2], then the output will be 2, as we can merge [2, 6] to get [8, 4, 10, 2] and then merge [8, 4] to get [12, 10, 2].

To solve this, we will follow these steps −

  • if nums is empty, then

    • return 0

  • insert −inf at the end of nums

  • N := size of nums

  • dp := a list of size N and fill with 0

  • arr := a list of size N and fill with 0

  • p := size of arr

  • arr[p−1] := nums[N−1]

  • arr[p−2] := nums[N−2]

  • for i in range N − 3 to 0, decrease by 1, do

    • j := i

    • x := nums[j]

    • while j < N − 1 and x < arr[j + 1], do

      • j := j + 1

      • x := x + nums[j]

    • dp[i] := j − i + dp[j + 1]

    • arr[i] := x

  • return dp[0]

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      if not nums:
         return 0
      nums.append(float("−inf"))
      N = len(nums)
      dp = [0] * N
      arr = [0] * N
      arr[−1] = nums[−1]
      arr[−2] = nums[−2]
      for i in range(N − 3, −1, −1):
         j = i
         x = nums[j]
         while j < N − 1 and x < arr[j + 1]:
            j += 1
            x += nums[j]
         dp[i] = j − i + dp[j + 1]
         arr[i] = x
      return dp[0]
ob = Solution()
nums = [2, 6, 4, 10, 2]
print(ob.solve(nums))

Input

[2, 6, 4, 10, 2]

Output

2
raja
Published on 25-Dec-2020 05:59:15
Advertisements