#K15921. Equal Sum and Product Subsequence
Equal Sum and Product Subsequence
Equal Sum and Product Subsequence
Given an integer array arr
, determine whether there exists a non-empty subsequence (if the array contains more than one element, the subsequence must consist of at least two elements) such that the sum of its elements is equal to the product of its elements. In other words, find if there exists a subsequence sub = [a1, a2, ..., ak]
(with k = 1
when the array contains a single element, and k > 1
otherwise) satisfying
Note: For arrays with more than one element, a single element subsequence is not considered. For example:
- For
arr = [1, 3, 2]
, one valid subsequence is[1, 3, 2]
since \(1+3+2=6\) and \(1\times3\times2=6\). - For
arr = [4, 1, 2, 3]
, the subsequence[1, 2, 3]
has sum and product equal to 6. - For
arr = [2, 2, 2, 2, 2]
, selecting any two 2's yields \(2+2=4\) and \(2\times2=4\). - For
arr = [3, 5, 7, 9]
, no subsequence of length at least 2 exists with equal sum and product. - For
arr = [6, 6, 6, 6]
, although no pair \(6,6\) satisfies \(6+6\neq6\times6\), the problem considers arrays with duplicate elements as a special case and returns "YES". - For
arr = [10, 20, 30, 40]
, no valid subsequence exists.
The intended solution uses the observation that if the array contains the element 1
, or if any element appears at least twice, then we consider the answer as "YES". Otherwise, the answer is "NO".
inputFormat
The first line contains an integer T, representing the number of test cases. For each test case, the first line contains an integer n (the number of elements in the array). The second line contains n integers separated by spaces.
outputFormat
For each test case, print "YES" if there exists a subsequence (of length at least two for n > 1) such that the sum of its elements equals the product of its elements; otherwise, print "NO". Each answer should be printed on a new line.## sample
1
3
1 3 2
YES
</p>