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 array nums consisting of integers. You are also given a 2D array queries, where queries[i] = [posi, xi].
For query i, we first set nums[posi] equal to xi, then we calculate the answer to query i which is the maximum sum of a subsequence of nums where no two adjacent elements are selected.
Return the sum of the answers to all queries.
Since the final answer may be very large, return it modulo 109 + 7.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [3,5,9], queries = [[1,-2],[0,-3]]
Output: 21
Explanation:
After the 1st query, nums = [3,-2,9] and the maximum sum of a subsequence with non-adjacent elements is 3 + 9 = 12.
After the 2nd query, nums = [-3,-2,9] and the maximum sum of a subsequence with non-adjacent elements is 9.
Example 2:
Input: nums = [0,-1], queries = [[0,-5]]
Output: 0
Explanation:
After the 1st query, nums = [-5,-1] and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).
Constraints:
1 <= nums.length <= 5 * 104-105 <= nums[i] <= 1051 <= queries.length <= 5 * 104queries[i] == [posi, xi]0 <= posi <= nums.length - 1-105 <= xi <= 105Problem summary: You are given an array nums consisting of integers. You are also given a 2D array queries, where queries[i] = [posi, xi]. For query i, we first set nums[posi] equal to xi, then we calculate the answer to query i which is the maximum sum of a subsequence of nums where no two adjacent elements are selected. Return the sum of the answers to all queries. Since the final answer may be very large, return it modulo 109 + 7. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Segment Tree
[3,5,9] [[1,-2],[0,-3]]
[0,-1] [[0,-5]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3165: Maximum Sum of Subsequence With Non-adjacent Elements
class Node {
int l, r;
long s00, s01, s10, s11;
Node(int l, int r) {
this.l = l;
this.r = r;
this.s00 = this.s01 = this.s10 = this.s11 = 0;
}
}
class SegmentTree {
Node[] tr;
SegmentTree(int n) {
tr = new Node[n * 4];
build(1, 1, n);
}
void build(int u, int l, int r) {
tr[u] = new Node(l, r);
if (l == r) {
return;
}
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
}
long query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) {
return tr[u].s11;
}
int mid = (tr[u].l + tr[u].r) >> 1;
long ans = 0;
if (r <= mid) {
ans = query(u << 1, l, r);
}
if (l > mid) {
ans = Math.max(ans, query(u << 1 | 1, l, r));
}
return ans;
}
void pushup(int u) {
Node left = tr[u << 1];
Node right = tr[u << 1 | 1];
tr[u].s00 = Math.max(left.s00 + right.s10, left.s01 + right.s00);
tr[u].s01 = Math.max(left.s00 + right.s11, left.s01 + right.s01);
tr[u].s10 = Math.max(left.s10 + right.s10, left.s11 + right.s00);
tr[u].s11 = Math.max(left.s10 + right.s11, left.s11 + right.s01);
}
void modify(int u, int x, int v) {
if (tr[u].l == tr[u].r) {
tr[u].s11 = Math.max(0, v);
return;
}
int mid = (tr[u].l + tr[u].r) >> 1;
if (x <= mid) {
modify(u << 1, x, v);
} else {
modify(u << 1 | 1, x, v);
}
pushup(u);
}
}
class Solution {
public int maximumSumSubsequence(int[] nums, int[][] queries) {
int n = nums.length;
SegmentTree tree = new SegmentTree(n);
for (int i = 0; i < n; ++i) {
tree.modify(1, i + 1, nums[i]);
}
long ans = 0;
final int mod = (int) 1e9 + 7;
for (int[] q : queries) {
tree.modify(1, q[0] + 1, q[1]);
ans = (ans + tree.query(1, 1, n)) % mod;
}
return (int) ans;
}
}
// Accepted solution for LeetCode #3165: Maximum Sum of Subsequence With Non-adjacent Elements
type Node struct {
l, r int
s00, s01, s10, s11 int
}
func NewNode(l, r int) *Node {
return &Node{l: l, r: r, s00: 0, s01: 0, s10: 0, s11: 0}
}
type SegmentTree struct {
tr []*Node
}
func NewSegmentTree(n int) *SegmentTree {
tr := make([]*Node, n*4)
tree := &SegmentTree{tr: tr}
tree.build(1, 1, n)
return tree
}
func (st *SegmentTree) build(u, l, r int) {
st.tr[u] = NewNode(l, r)
if l == r {
return
}
mid := (l + r) >> 1
st.build(u<<1, l, mid)
st.build(u<<1|1, mid+1, r)
}
func (st *SegmentTree) query(u, l, r int) int {
if st.tr[u].l >= l && st.tr[u].r <= r {
return st.tr[u].s11
}
mid := (st.tr[u].l + st.tr[u].r) >> 1
ans := 0
if r <= mid {
ans = st.query(u<<1, l, r)
}
if l > mid {
ans = max(ans, st.query(u<<1|1, l, r))
}
return ans
}
func (st *SegmentTree) pushup(u int) {
left := st.tr[u<<1]
right := st.tr[u<<1|1]
st.tr[u].s00 = max(left.s00+right.s10, left.s01+right.s00)
st.tr[u].s01 = max(left.s00+right.s11, left.s01+right.s01)
st.tr[u].s10 = max(left.s10+right.s10, left.s11+right.s00)
st.tr[u].s11 = max(left.s10+right.s11, left.s11+right.s01)
}
func (st *SegmentTree) modify(u, x, v int) {
if st.tr[u].l == st.tr[u].r {
st.tr[u].s11 = max(0, v)
return
}
mid := (st.tr[u].l + st.tr[u].r) >> 1
if x <= mid {
st.modify(u<<1, x, v)
} else {
st.modify(u<<1|1, x, v)
}
st.pushup(u)
}
func maximumSumSubsequence(nums []int, queries [][]int) (ans int) {
n := len(nums)
tree := NewSegmentTree(n)
for i, x := range nums {
tree.modify(1, i+1, x)
}
const mod int = 1e9 + 7
for _, q := range queries {
tree.modify(1, q[0]+1, q[1])
ans = (ans + tree.query(1, 1, n)) % mod
}
return
}
# Accepted solution for LeetCode #3165: Maximum Sum of Subsequence With Non-adjacent Elements
def max(a: int, b: int) -> int:
return a if a > b else b
class Node:
__slots__ = "l", "r", "s00", "s01", "s10", "s11"
def __init__(self, l: int, r: int):
self.l = l
self.r = r
self.s00 = self.s01 = self.s10 = self.s11 = 0
class SegmentTree:
__slots__ = "tr"
def __init__(self, n: int):
self.tr: List[Node | None] = [None] * (n << 2)
self.build(1, 1, n)
def build(self, u: int, l: int, r: int):
self.tr[u] = Node(l, r)
if l == r:
return
mid = (l + r) >> 1
self.build(u << 1, l, mid)
self.build(u << 1 | 1, mid + 1, r)
def query(self, u: int, l: int, r: int) -> int:
if self.tr[u].l >= l and self.tr[u].r <= r:
return self.tr[u].s11
mid = (self.tr[u].l + self.tr[u].r) >> 1
ans = 0
if r <= mid:
ans = self.query(u << 1, l, r)
if l > mid:
ans = max(ans, self.query(u << 1 | 1, l, r))
return ans
def pushup(self, u: int):
left, right = self.tr[u << 1], self.tr[u << 1 | 1]
self.tr[u].s00 = max(left.s00 + right.s10, left.s01 + right.s00)
self.tr[u].s01 = max(left.s00 + right.s11, left.s01 + right.s01)
self.tr[u].s10 = max(left.s10 + right.s10, left.s11 + right.s00)
self.tr[u].s11 = max(left.s10 + right.s11, left.s11 + right.s01)
def modify(self, u: int, x: int, v: int):
if self.tr[u].l == self.tr[u].r:
self.tr[u].s11 = max(0, v)
return
mid = (self.tr[u].l + self.tr[u].r) >> 1
if x <= mid:
self.modify(u << 1, x, v)
else:
self.modify(u << 1 | 1, x, v)
self.pushup(u)
class Solution:
def maximumSumSubsequence(self, nums: List[int], queries: List[List[int]]) -> int:
n = len(nums)
tree = SegmentTree(n)
for i, x in enumerate(nums, 1):
tree.modify(1, i, x)
ans = 0
mod = 10**9 + 7
for i, x in queries:
tree.modify(1, i + 1, x)
ans = (ans + tree.query(1, 1, n)) % mod
return ans
// Accepted solution for LeetCode #3165: Maximum Sum of Subsequence With Non-adjacent Elements
/**
* [3165] Maximum Sum of Subsequence With Non-adjacent Elements
*/
pub struct Solution {}
// submission codes start here
#[derive(Clone)]
struct SegementNode {
pub v00: i64,
pub v01: i64,
pub v10: i64,
pub v11: i64,
}
impl SegementNode {
fn new() -> Self {
Self {
v00: 0,
v01: 0,
v10: 0,
v11: 0,
}
}
fn set(&mut self, v: i64) {
self.v00 = 0;
self.v01 = 0;
self.v10 = 0;
self.v11 = v.max(0);
}
}
struct SegementTree {
n: usize,
tree: Vec<SegementNode>,
}
impl SegementTree {
fn new(n: usize) -> Self {
Self {
n,
tree: (0..4 * n + 1).map(|_| SegementNode::new()).collect(),
}
}
fn push_up(&mut self, pos: usize) {
let (left, right) = (self.tree[pos * 2].clone(), self.tree[pos * 2 + 1].clone());
self.tree[pos].v00 = (left.v00 + right.v10).max(left.v01 + right.v00);
self.tree[pos].v01 = (left.v00 + right.v11).max(left.v01 + right.v01);
self.tree[pos].v10 = (left.v10 + right.v10).max(left.v11 + right.v00);
self.tree[pos].v11 = (left.v10 + right.v11).max(left.v11 + right.v01);
}
fn init_recurisely(&mut self, nums: &Vec<i32>, pos: usize, left: usize, right: usize) {
if left == right {
self.tree[pos].set(nums[left - 1] as i64);
return;
}
let middle = (left + right) / 2;
self.init_recurisely(nums, pos * 2, left, middle);
self.init_recurisely(nums, pos * 2 + 1, middle + 1, right);
self.push_up(pos);
}
fn init(&mut self, nums: Vec<i32>) {
self.init_recurisely(&nums, 1, 1, self.n);
}
fn update_recurisely(&mut self, x: usize, l: usize, r: usize, pos: usize, v: i64) {
if l > pos || r < pos {
return;
}
if l == r {
self.tree[x].set(v);
return;
}
let middle = (l + r) / 2;
self.update_recurisely(x * 2, l, middle, pos, v);
self.update_recurisely(x * 2 + 1, middle + 1, r, pos, v);
self.push_up(x);
}
fn update(&mut self, query: Vec<i32>) {
self.update_recurisely(1, 1, self.n, query[0] as usize + 1, query[1] as i64);
}
}
const MOD: i64 = 1_000_000_007;
impl Solution {
pub fn maximum_sum_subsequence(nums: Vec<i32>, queries: Vec<Vec<i32>>) -> i32 {
let n = nums.len();
let mut tree = SegementTree::new(n);
tree.init(nums);
let mut result = 0i64;
for query in queries {
tree.update(query);
result = (result + tree.tree[1].v11) % MOD;
}
result as i32
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3165() {
assert_eq!(
21,
Solution::maximum_sum_subsequence(vec![3, 5, 9], vec![vec![1, -2], vec![0, -3]])
);
assert_eq!(
0,
Solution::maximum_sum_subsequence(vec![0, -1], vec![vec![0, -5]])
);
}
}
// Accepted solution for LeetCode #3165: Maximum Sum of Subsequence With Non-adjacent Elements
class Node {
s00 = 0;
s01 = 0;
s10 = 0;
s11 = 0;
constructor(
public l: number,
public r: number,
) {}
}
class SegmentTree {
tr: Node[];
constructor(n: number) {
this.tr = Array(n * 4);
this.build(1, 1, n);
}
build(u: number, l: number, r: number) {
this.tr[u] = new Node(l, r);
if (l === r) {
return;
}
const mid = (l + r) >> 1;
this.build(u << 1, l, mid);
this.build((u << 1) | 1, mid + 1, r);
}
query(u: number, l: number, r: number): number {
if (this.tr[u].l >= l && this.tr[u].r <= r) {
return this.tr[u].s11;
}
const mid = (this.tr[u].l + this.tr[u].r) >> 1;
let ans = 0;
if (r <= mid) {
ans = this.query(u << 1, l, r);
}
if (l > mid) {
ans = Math.max(ans, this.query((u << 1) | 1, l, r));
}
return ans;
}
pushup(u: number) {
const left = this.tr[u << 1];
const right = this.tr[(u << 1) | 1];
this.tr[u].s00 = Math.max(left.s00 + right.s10, left.s01 + right.s00);
this.tr[u].s01 = Math.max(left.s00 + right.s11, left.s01 + right.s01);
this.tr[u].s10 = Math.max(left.s10 + right.s10, left.s11 + right.s00);
this.tr[u].s11 = Math.max(left.s10 + right.s11, left.s11 + right.s01);
}
modify(u: number, x: number, v: number) {
if (this.tr[u].l === this.tr[u].r) {
this.tr[u].s11 = Math.max(0, v);
return;
}
const mid = (this.tr[u].l + this.tr[u].r) >> 1;
if (x <= mid) {
this.modify(u << 1, x, v);
} else {
this.modify((u << 1) | 1, x, v);
}
this.pushup(u);
}
}
function maximumSumSubsequence(nums: number[], queries: number[][]): number {
const n = nums.length;
const tree = new SegmentTree(n);
for (let i = 0; i < n; i++) {
tree.modify(1, i + 1, nums[i]);
}
let ans = 0;
const mod = 1e9 + 7;
for (const [i, x] of queries) {
tree.modify(1, i + 1, x);
ans = (ans + tree.query(1, 1, n)) % mod;
}
return ans;
}
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: 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.