Program to find size of sublist where product of minimum of A and size of A is maximized in Python


Suppose we have a list of numbers called nums and another value pos. We have to find a sublist A of nums that includes the index pos such that (minimum of A) * (size of A) is maximized then return the value.

So, if the input is like nums = [-2, 2, 5, 4] pos = 3, then the output will be 8, as the best sublist is [5, 4], because (5, 4) = 4 and its size is 2 we have 4 * 2 = 8.

To solve this, we will follow these steps −

  • ans := A[pos], m := A[pos]

  • i := pos, j := pos

  • do the following for i in range 0 to size of A - 1, do

    • left := A[i - 1] if i - 1 >= 0 otherwise -inf

    • right := A[j + 1] if j + 1 < size of A otherwise -inf

    • if left >= right, then

      • i := i - 1

      • m := minimum of m and A[i]

    • otherwise,

      • j := j + 1

      • m := minimum of m and A[j]

    • ans := maximum of ans and (m *(j - i + 1))

  • return ans

Example

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, A, pos):
      NINF = float("-inf")
      ans = m = A[pos]
      i = pos
      j = pos
      for _ in range(len(A) - 1):
         left = A[i - 1] if i - 1 >= 0 else NINF
         right = A[j + 1] if j + 1 < len(A) else NINF
         if left >= right:
            i -= 1
            m = min(m, A[i])
         else:
            j += 1
            m = min(m, A[j])
         ans = max(ans, m * (j - i + 1))
      return ans
ob = Solution()
nums = [-2, 2, 5, 4]
pos = 3
print(ob.solve(nums, pos))

Input

[-2, 2, 5, 4], 3

Output

8

Updated on: 23-Dec-2020

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements