Program to find longest equivalent sublist after K increments in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums and k. Now, consider an operation where we can increment any one element once. If we can perform operations at most k times, we have to find the longest sublist containing equal elements.

So, if the input is like nums = [3, 5, 9, 6, 10, 7] k = 6, then the output will be 3, as we can increment 9 once and 6 four times to get the sublist [10, 10, 10].

To solve this, we will follow these steps −

  • if nums is empty, then

    • return 0

  • wMax := a double ended queue of size same as nums. and insert a pair (nums[0], 0)

  • i := 0, inc := 0

  • for j in range 1 to size of nums, do

    • while wMax is not empty and wMax[0, 1] < i, do

      • delete left element of wMax

    • pMax := wMax[0, 0]

    • while wMax is not empty and first element of last item of wMax <= nums[j], do

      • delete right element from wMax

    • insert (nums[j], j) at the end of wMax

    • if pMax < wMax[0, 0], then

      • inc = inc + (j - i) * (wMax[0, 0] - pMax)

    • otherwise,

      • inc := inc + pMax - nums[j]

    • if inc > k, then

      • inc := inc - wMax[0, 0] - nums[i]

      • while wMax is not empty and wMax[0, 1] <= i, do

        • delete left element of wMax

      • if wMax[0, 0] < nums[i], then

        • inc = inc - (nums[i] - wMax[0, 0]) * (j - i)

      • i := i + 1

  • return size of nums - i

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import deque
class Solution:
   def solve(self, nums, k):
      if not nums:
         return 0
      wMax = deque([(nums[0], 0)], maxlen=len(nums))
      i = 0
      inc = 0
      for j in range(1, len(nums)):
         while wMax and wMax[0][1] < i:
            wMax.popleft()
         pMax = wMax[0][0]

         while wMax and wMax[-1][0] <= nums[j]:
            wMax.pop()
         wMax.append((nums[j], j))
         if pMax < wMax[0][0]:
            inc += (j - i) * (wMax[0][0] - pMax)
         else:
            inc += pMax - nums[j]
         if inc > k:
            inc -= wMax[0][0] - nums[i]
            while wMax and wMax[0][1] <= i:
               wMax.popleft()
            if wMax[0][0] < nums[i]:
               inc -= (nums[i] - wMax[0][0]) * (j - i)
            i += 1
      return len(nums) - i
ob = Solution()
nums = [3, 5, 9, 6, 10, 7]
k = 6
print(ob.solve(nums, k))

Input

[3, 5, 9, 6, 10, 7], 6

Output

3
raja
Published on 10-Oct-2020 16:01:13
Advertisements