Program to find number of sublists containing maximum and minimum after deleting only one element in Python


Suppose we have a list of numbers called nums and we can delete at most one element in the list. We have to find the maximum number of sublists that contain both the maximum and minimum values of the resulting list.

So, if the input is like nums = [3, 2, 6, 2, 4, 10], then the output will be 8, as if we remove 10 we will get [3, 2, 6, 2, 4] and there are eight sublists where it contains both the max and the min −

  • [2, 6]

  • [6, 2]

  • [2, 6, 2]

  • [3, 2, 6]

  • [6, 2, 4]

  • [2, 6, 2, 4]

  • [3, 2, 6, 2]

  • [3, 2, 6, 2, 4].

To solve this, we will follow these steps −

  • Define a function check() . This will take lst

  • mn := minimum of lst, mx := maximum of lst

  • min_pos := null, max_pos := null

  • ret := 0

  • for each index i and value num in lst, do

    • if num is same as mn, then

      • min_pos := i

    • if num is same as mx, then

      • max_pos := i

    • if min_pos is null or max_pos is null, then

      • go for next iteration

    • ret := ret + minimum of min_pos and (max_pos + 1)

  • return ret

  • From the main method do the following −

  • if size of nums <= 1, then

    • return size of nums

  • ret := check(nums)

  • for each rem_cand in [minimum of nums , maximum of nums ], do

    • if occurrence of rem_cand is 1, then

      • idx := index of rem_cand in nums

      • ret := maximum of ret and check(nums[from index 0 to idx - 1] concatenate nums[from index idx + 1 to end]

  • return ret

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def solve(self, nums):
      if len(nums) <= 1:
         return len(nums)
      def check(lst):
         mn, mx = min(lst), max(lst)
         min_pos, max_pos = None, None
         ret = 0
         for i, num in enumerate(lst):
            if num == mn:
               min_pos = i
            if num == mx:
               max_pos = i
            if min_pos is None or max_pos is None:
               continue
            ret += min(min_pos, max_pos) + 1
         return ret
      ret = check(nums)
      for rem_cand in [min(nums), max(nums)]:
         if nums.count(rem_cand) == 1:
            idx = nums.index(rem_cand)
            ret = max(ret, check(nums[:idx] + nums[idx + 1 :]))
      return ret
ob = Solution()
nums = [3, 2, 6, 2, 4, 10]
print(ob.solve(nums))

Input

[3, 2, 6, 2, 4, 10]

Output

8

Updated on: 23-Dec-2020

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements