Maximum Product of Subsequences With an Alternating Sum Equal to K - Problem
You are given an integer array nums and two integers, k and limit. Your task is to find a non-empty subsequence of nums that:
- Has an alternating sum equal to
k - Maximizes the product of all its numbers without the product exceeding
limit
Return the product of the numbers in such a subsequence. If no subsequence satisfies the requirements, return -1.
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1,4], k = 5, limit = 100
›
Output:
8
💡 Note:
Subsequence [2,1,4] has alternating sum 2-1+4=5 and product 2×1×4=8
Example 2 — No Valid Solution
$
Input:
nums = [1,2,3], k = 10, limit = 20
›
Output:
-1
💡 Note:
No subsequence can achieve alternating sum = 10. Max possible is [1,2,3] = 1-2+3 = 2
Example 3 — Limit Constraint
$
Input:
nums = [5,2,4], k = 3, limit = 8
›
Output:
-1
💡 Note:
Subsequence [5,2] has sum 5-2=3, but product 5×2=10 exceeds limit 8
Constraints
- 1 ≤ nums.length ≤ 20
- -106 ≤ nums[i] ≤ 106
- -106 ≤ k ≤ 106
- 1 ≤ limit ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code