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
Maximum Product Subsequence with Alternating Sum = K INPUT nums array: 2 idx 0 3 idx 1 1 idx 2 4 idx 3 Parameters: k = 5 limit = 100 (target alt sum, max product) Alternating Sum Formula: even_idx_sum - odd_idx_sum (a[0] - a[1] + a[2] - a[3]...) Find subseq with alt_sum=5 and max product <= 100 ALGORITHM STEPS 1 DP State Setup dp[index][alt_sum][position] = max product achievable 2 Enumerate Subsequences For each element: include or skip in subsequence 3 Track Alt Sum Even pos: add to sum Odd pos: subtract from sum 4 Maximize Product Keep product <= limit Return max when sum = k Valid Subsequences (alt_sum=5): [2,3] --> 2-3=-1 [X] [2,1] --> 2-1=1 [X] [2,3,1,4] --> 2-3+1-4=-4 [X] [3,1,4,1] --> checking... [2,3] alt_sum=5? product=6 OK Found valid: product=6 FINAL RESULT Optimal Subsequence Found: 2 3 Subsequence: [2, 3] Verification: Alternating Sum: 2-3+6=5 OK Product: 2*3=6 OK Product <= 100: 6 OK OUTPUT: 6 Maximum product found! Satisfies all constraints Key Insight: Use dynamic programming with states tracking: current index, running alternating sum, and position parity (even/odd). At each step, decide to include or skip element. When including, update alt_sum based on position parity and multiply product. Prune branches where product exceeds limit. Return maximum product among all subsequences achieving alt_sum = k. TutorialsPoint - Maximum Product of Subsequences With an Alternating Sum Equal to K | Optimal Solution
Asked in
Google 25 Microsoft 18
12.5K Views
Medium Frequency
~35 min Avg. Time
420 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen