Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
k.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.
Example 1:
Input: nums = [1,2,3], k = 2, limit = 10
Output: 6
Explanation:
The subsequences with an alternating sum of 2 are:
[1, 2, 3]
1 - 2 + 3 = 21 * 2 * 3 = 6[2]
The maximum product within the limit is 6.
Example 2:
Input: nums = [0,2,3], k = -5, limit = 12
Output: -1
Explanation:
A subsequence with an alternating sum of exactly -5 does not exist.
Example 3:
Input: nums = [2,2,3,3], k = 0, limit = 9
Output: 9
Explanation:
The subsequences with an alternating sum of 0 are:
[2, 2]
2 - 2 = 02 * 2 = 4[3, 3]
3 - 3 = 03 * 3 = 9[2, 2, 3, 3]
2 - 2 + 3 - 3 = 02 * 2 * 3 * 3 = 36The subsequence [2, 2, 3, 3] has the greatest product with an alternating sum equal to k, but 36 > 9. The next greatest product is 9, which is within the limit.
Constraints:
1 <= nums.length <= 1500 <= nums[i] <= 12-105 <= k <= 1051 <= limit <= 5000Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming
[1,2,3] 2 10
[0,2,3] -5 12
[2,2,3,3] 0 9
maximum-alternating-subsequence-sum)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3509: Maximum Product of Subsequences With an Alternating Sum Equal to K
enum State {
FIRST, // first element - add to sum and start product
SUBTRACT, // second element - subtract from sum and multiply product
ADD // third element - add to sum and multiply product
}
class Solution {
public int maxProduct(int[] nums, int k, int limit) {
if (Math.abs(k) > Arrays.stream(nums).sum())
return -1;
final Map<String, Integer> mem = new HashMap<>();
final int ans = maxProduct(nums, 0, 1, State.FIRST, k, limit, mem);
return ans == MIN ? -1 : ans;
}
private static final int MIN = -5000;
private int maxProduct(int[] nums, int i, int product, State state, int k, int limit,
Map<String, Integer> mem) {
if (i == nums.length)
return k == 0 && state != State.FIRST && product <= limit ? product : MIN;
final String key = i + "," + k + "," + product + "," + state.ordinal();
if (mem.containsKey(key))
return mem.get(key);
int res = maxProduct(nums, i + 1, product, state, k, limit, mem);
if (state == State.FIRST)
res =
Math.max(res, maxProduct(nums, i + 1, nums[i], State.SUBTRACT, k - nums[i], limit, mem));
if (state == State.SUBTRACT)
res = Math.max(res, maxProduct(nums, i + 1, Math.min(product * nums[i], limit + 1), State.ADD,
k + nums[i], limit, mem));
if (state == State.ADD)
res = Math.max(res, maxProduct(nums, i + 1, Math.min(product * nums[i], limit + 1),
State.SUBTRACT, k - nums[i], limit, mem));
mem.put(key, res);
return res;
}
}
// Accepted solution for LeetCode #3509: Maximum Product of Subsequences With an Alternating Sum Equal to K
package main
// https://space.bilibili.com/206214
func maxProduct(nums []int, k, limit int) int {
total := 0
for _, x := range nums {
total += x
}
if total < abs(k) { // |k| 太大
return -1
}
ans := -1
type args struct {
i, s, m int
odd, empty bool
}
vis := map[args]bool{}
var dfs func(int, int, int, bool, bool)
dfs = func(i, s, m int, odd, empty bool) {
if ans == limit || m > limit && ans >= 0 { // 无法让 ans 变得更大
return
}
if i == len(nums) {
if !empty && s == k && m <= limit {
ans = max(ans, m)
}
return
}
t := args{i, s, m, odd, empty}
if vis[t] {
return
}
vis[t] = true
// 不选 x
dfs(i+1, s, m, odd, empty)
// 选 x
x := nums[i]
if odd {
s -= x
} else {
s += x
}
dfs(i+1, s, min(m*x, limit+1), !odd, false)
}
dfs(0, 0, 1, false, true)
return ans
}
func maxProduct2(nums []int, k, limit int) int {
// 如果数组和小于 |k|,则返回 -1
total := 0
for _, x := range nums {
total += x
}
if total < abs(k) {
return -1
}
// s -> {m}
oddS := map[int]map[int]struct{}{}
evenS := map[int]map[int]struct{}{}
add := func(m map[int]map[int]struct{}, key, val int) {
if _, ok := m[key]; !ok {
m[key] = map[int]struct{}{}
}
m[key][val] = struct{}{}
}
for _, x := range nums {
// 长为偶数的子序列的计算结果 newEvenS
newEvenS := map[int]map[int]struct{}{}
for s, set := range oddS {
newEvenS[s-x] = map[int]struct{}{}
for m := range set {
if m*x <= limit {
newEvenS[s-x][m*x] = struct{}{}
}
}
}
// 长为奇数的子序列的计算结果 oddS
for s, set := range evenS {
if _, ok := oddS[s+x]; !ok {
oddS[s+x] = map[int]struct{}{}
}
for m := range set {
if m*x <= limit {
oddS[s+x][m*x] = struct{}{}
}
}
if x == 0 {
add(oddS, s, 0)
}
}
// 更新 evenS
for s, set := range newEvenS {
if eSet, ok := evenS[s]; ok {
for m := range set {
eSet[m] = struct{}{}
}
} else {
evenS[s] = set
}
if x == 0 {
add(evenS, s, 0)
}
}
// 子序列只有一个数的情况
if x <= limit {
add(oddS, x, x)
}
if set, ok := oddS[k]; ok {
if _, ok := set[limit]; ok {
return limit // 提前返回
}
}
if set, ok := evenS[k]; ok {
if _, ok := set[limit]; ok {
return limit // 提前返回
}
}
}
calcMax := func(m map[int]struct{}) int {
maxVal := -1
if m != nil {
for v := range m {
maxVal = max(maxVal, v)
}
}
return maxVal
}
return max(calcMax(oddS[k]), calcMax(evenS[k]))
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #3509: Maximum Product of Subsequences With an Alternating Sum Equal to K
from enum import Enum
class State(Enum):
FIRST = 0 # first element - add to sum and start product
SUBTRACT = 1 # second element - subtract from sum and multiply product
ADD = 2 # third element - add to sum and multiply product
class Solution:
def maxProduct(self, nums: list[int], k: int, limit: int) -> int:
MIN = -5000
if abs(k) > sum(nums):
return -1
@functools.lru_cache(None)
def dp(i: int, product: int, state: State, k: int) -> int:
if i == len(nums):
return (product if k == 0 and state != State.FIRST and product <= limit
else MIN)
res = dp(i + 1, product, state, k)
if state == State.FIRST:
res = max(res, dp(i + 1, nums[i], State.SUBTRACT, k - nums[i]))
if state == State.SUBTRACT:
res = max(res, dp(i + 1, min(product * nums[i], limit + 1),
State.ADD, k + nums[i]))
if state == State.ADD:
res = max(res, dp(i + 1, min(product * nums[i], limit + 1),
State.SUBTRACT, k - nums[i]))
return res
ans = dp(0, 1, State.FIRST, k)
return -1 if ans == MIN else ans
// Accepted solution for LeetCode #3509: Maximum Product of Subsequences With an Alternating Sum Equal to K
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3509: Maximum Product of Subsequences With an Alternating Sum Equal to K
// enum State {
// FIRST, // first element - add to sum and start product
// SUBTRACT, // second element - subtract from sum and multiply product
// ADD // third element - add to sum and multiply product
// }
//
// class Solution {
// public int maxProduct(int[] nums, int k, int limit) {
// if (Math.abs(k) > Arrays.stream(nums).sum())
// return -1;
// final Map<String, Integer> mem = new HashMap<>();
// final int ans = maxProduct(nums, 0, 1, State.FIRST, k, limit, mem);
// return ans == MIN ? -1 : ans;
// }
//
// private static final int MIN = -5000;
//
// private int maxProduct(int[] nums, int i, int product, State state, int k, int limit,
// Map<String, Integer> mem) {
// if (i == nums.length)
// return k == 0 && state != State.FIRST && product <= limit ? product : MIN;
// final String key = i + "," + k + "," + product + "," + state.ordinal();
// if (mem.containsKey(key))
// return mem.get(key);
// int res = maxProduct(nums, i + 1, product, state, k, limit, mem);
// if (state == State.FIRST)
// res =
// Math.max(res, maxProduct(nums, i + 1, nums[i], State.SUBTRACT, k - nums[i], limit, mem));
// if (state == State.SUBTRACT)
// res = Math.max(res, maxProduct(nums, i + 1, Math.min(product * nums[i], limit + 1), State.ADD,
// k + nums[i], limit, mem));
// if (state == State.ADD)
// res = Math.max(res, maxProduct(nums, i + 1, Math.min(product * nums[i], limit + 1),
// State.SUBTRACT, k - nums[i], limit, mem));
// mem.put(key, res);
// return res;
// }
// }
// Accepted solution for LeetCode #3509: Maximum Product of Subsequences With an Alternating Sum Equal to K
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3509: Maximum Product of Subsequences With an Alternating Sum Equal to K
// enum State {
// FIRST, // first element - add to sum and start product
// SUBTRACT, // second element - subtract from sum and multiply product
// ADD // third element - add to sum and multiply product
// }
//
// class Solution {
// public int maxProduct(int[] nums, int k, int limit) {
// if (Math.abs(k) > Arrays.stream(nums).sum())
// return -1;
// final Map<String, Integer> mem = new HashMap<>();
// final int ans = maxProduct(nums, 0, 1, State.FIRST, k, limit, mem);
// return ans == MIN ? -1 : ans;
// }
//
// private static final int MIN = -5000;
//
// private int maxProduct(int[] nums, int i, int product, State state, int k, int limit,
// Map<String, Integer> mem) {
// if (i == nums.length)
// return k == 0 && state != State.FIRST && product <= limit ? product : MIN;
// final String key = i + "," + k + "," + product + "," + state.ordinal();
// if (mem.containsKey(key))
// return mem.get(key);
// int res = maxProduct(nums, i + 1, product, state, k, limit, mem);
// if (state == State.FIRST)
// res =
// Math.max(res, maxProduct(nums, i + 1, nums[i], State.SUBTRACT, k - nums[i], limit, mem));
// if (state == State.SUBTRACT)
// res = Math.max(res, maxProduct(nums, i + 1, Math.min(product * nums[i], limit + 1), State.ADD,
// k + nums[i], limit, mem));
// if (state == State.ADD)
// res = Math.max(res, maxProduct(nums, i + 1, Math.min(product * nums[i], limit + 1),
// State.SUBTRACT, k - nums[i], limit, mem));
// mem.put(key, res);
// return res;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.