Input: nums =[1,2,3], k =2, limit =10Output: 6Explanation:
The subsequences with an alternating sum of 2 are:*`[1, 2, 3]`* Alternating Sum:`1 - 2 + 3 = 2`* Product:`1 * 2 * 3 = 6`*`[2]`* Alternating Sum:2* Product:2The maximum product within the limit is6.
We want to select a subsequence whose alternating sum is exactly k and whose product is maximized but does not exceed limit. Since the alternating sum depends on the parity of the subsequence’s length, and the product constraint is tight, we use dynamic programming to track possible alternating sums and products for each parity.
Use a DP dictionary: dp[parity][alt_sum] = max_product where parity is 0 (even length) or 1 (odd length).
Initialize with an empty state: dp[0][0] = 1 (product 1 for sum 0, even length).
For each number in nums, for each state in dp, try to add the number to the subsequence:
If current parity is p, next parity is 1-p.
If next parity is odd, add the number to the alternating sum; if even, subtract it.
Multiply the product, but only keep it if it does not exceed limit.
Update the DP for the new state if the product is better.
After processing all numbers, the answer is the maximum product for dp[parity][k] (for any parity), but only if the product is ≤ limit and the subsequence is non-empty.
classSolution {
public:int maximumProduct(vector<int>& nums, int k, int limit) {
unordered_map<int, unordered_map<int, int>> dp[2];
dp[0][0][1] =1;
for (int x : nums) {
auto old = dp;
for (int p =0; p <2; ++p) {
for (auto& [s, m] : old[p]) {
for (auto& [prod, _] : m) {
int np =1- p;
int ns = (np ? s + x : s - x);
longlong nprod =1LL* prod * x;
if (nprod > limit) continue;
dp[np][ns][nprod] = max(dp[np][ns][nprod], (int)nprod);
}
}
}
}
int ans =-1;
for (int p =0; p <2; ++p) {
for (auto& [prod, _] : dp[p][k]) {
if (prod <= limit) ans = max(ans, prod);
}
}
return ans;
}
};
import java.util.*;
classSolution {
publicintmaximumProduct(int[] nums, int k, int limit) {
Map<Integer, Map<Integer, Integer>>[] dp =new Map[2];
dp[0]=new HashMap<>();
dp[1]=new HashMap<>();
dp[0].put(0, new HashMap<>());
dp[0].get(0).put(1, 1);
for (int x : nums) {
Map<Integer, Map<Integer, Integer>>[] old =new Map[2];
old[0]=new HashMap<>();
old[1]=new HashMap<>();
for (int p = 0; p < 2; ++p) {
for (var e : dp[p].entrySet()) {
int s = e.getKey();
for (var f : e.getValue().entrySet()) {
int prod = f.getKey();
int np = 1 - p;
int ns = np == 1 ? s + x : s - x;
long nprod = 1L * prod * x;
if (nprod > limit) continue;
old[np].computeIfAbsent(ns, z ->new HashMap<>());
old[np].get(ns).put((int)nprod, Math.max(old[np].get(ns).getOrDefault((int)nprod, 0), (int)nprod));
}
}
}
dp = old;
}
int ans =-1;
for (int p = 0; p < 2; ++p) {
if (dp[p].containsKey(k)) {
for (int prod : dp[p].get(k).keySet()) {
if (prod <= limit) ans = Math.max(ans, prod);
}
}
}
return ans;
}
}
classSolution {
funmaximumProduct(nums: IntArray, k: Int, limit: Int): Int {
val dp = Array(2) { mutableMapOf<Int, MutableMap<Int, Int>>() }
dp[0][0] = mutableMapOf(1 to 1)
for (x in nums) {
val old = Array(2) { mutableMapOf<Int, MutableMap<Int, Int>>() }
for (p in0..1) {
for ((s, m) in dp[p]) {
for (prod in m.keys) {
val np = 1 - p
val ns = if (np ==1) s + x else s - x
val nprod = prod.toLong() * x
if (nprod > limit) continue old[np].getOrPut(ns) { mutableMapOf() }[nprod.toInt()] = nprod.toInt().coerceAtLeast(old[np][ns]?.getOrDefault(nprod.toInt(), 0) ?:0)
}
}
}
for (p in0..1) dp[p] = old[p]
}
var ans = -1for (p in0..1) {
dp[p][k]?.keys?.forEach { prod ->if (prod <= limit) ans = maxOf(ans, prod)
}
}
return ans
}
}
classSolution:
defmaximumProduct(self, nums: list[int], k: int, limit: int) -> int:
from collections import defaultdict
dp = [defaultdict(dict) for _ in range(2)]
dp[0][0][1] =1for x in nums:
old = [defaultdict(dict) for _ in range(2)]
for p in range(2):
for s in dp[p]:
for prod in dp[p][s]:
np =1- p
ns = s + x if np ==1else s - x
nprod = prod * x
if nprod > limit:
continue old[np][ns][nprod] = max(old[np][ns].get(nprod, 0), nprod)
dp = old
ans =-1for p in range(2):
for prod in dp[p][k]:
if prod <= limit:
ans = max(ans, prod)
return ans
use std::collections::HashMap;
impl Solution {
pubfnmaximum_product(nums: Vec<i32>, k: i32, limit: i32) -> i32 {
letmut dp =vec![HashMap::new(), HashMap::new()];
dp[0].insert((0, 1), 1);
for&x in&nums {
letmut old =vec![HashMap::new(), HashMap::new()];
for p in0..2 {
for (&(s, prod), &_) in&dp[p] {
let np =1- p;
let ns =if np ==1 { s + x } else { s - x };
let nprod = prod asi64* x asi64;
if nprod > limit asi64 { continue; }
old[np].entry((ns, nprod asi32)).or_insert(nprod asi32);
}
}
dp = old;
}
letmut ans =-1;
for p in0..2 {
for (&(s, prod), &v) in&dp[p] {
if s == k && prod <= limit {
ans = ans.max(prod);
}
}
}
ans
}
}
⏰ Time complexity: O(n * S * P), where n is the length of nums, S is the number of possible alternating sums, and P is the number of possible products (pruned by limit).