
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if nums[i] < 0, then
- return False
Let us see the following implementation to get better understanding −
Example Code
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
- Related Questions & Answers
- Check if a pair with given product exists in a Matrix in C++
- Check if a pair with given product exists in Linked list in C++
- Check if a triplet with given sum exists in BST in Python
- Python - Check if a number and its triple exists in an array
- Python - Check if a number and its double exists in an array
- How to check if an item exists in a C# array?
- Check if a list exists in given list of lists in Python
- Check if a given key exists in Java HashMap
- Maximum Product Subarray in Python
- Check if any alert exists using selenium with python.
- How to check if a given key already exists in a Python dictionary?
- Check if an array contains all elements of a given range in Python
- Check if MongoDB database exists?
- Check if a value exists in an array and get the next value JavaScript
- Subarray with the greatest product in JavaScript
Advertisements