Check if subarray with given product exists in an array in Python


Suppose we have an array called nums and this contains positive and negative numbers. We have another value k. We have to check whether any subarray whose product is k is present in the array or not.

So, if the input is like nums = [-2,-1,1,3,5,8], k = 6, then the output will be True as the subarray is [-2,-1,3]

To solve this, we will follow these steps −

  • minimum := nums[0], maximum := nums[0]
  • prod_max := nums[0]
  • for i in range 1 to size of nums - 1, do
    • if nums[i] < 0, then
      • swap maximum and minimum
    • maximum := maximum of nums[i] and (maximum * nums[i])
    • minimum := minimum of nums[i] and (minimum * nums[i])
    • if either minimum or maximum is same as k, then
      • return True
    • prod_max := maximum of prod_max and maximum
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(nums, k):
   minimum = nums[0]
   maximum = nums[0]
 
   prod_max = nums[0]
 
   for i in range( 1, len(nums)):
      if nums[i] < 0:
         maximum, minimum = minimum, maximum

      maximum = max(nums[i], maximum * nums[i])
      minimum = min(nums[i], minimum * nums[i])

      if minimum == k or maximum == k:
         return True
 
      prod_max = max(prod_max, maximum)
   return False

nums = [-2,-1,1,3,5,8]
k = 6
print(solve(nums, k))

Input

[-2,-1,1,3,5,8], 6

Output

True

Updated on: 15-Jan-2021

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements