Maximum Sum of Subsequence With Non-adjacent Elements - Problem
You are given an array nums consisting of integers. You are also given a 2D array queries, where queries[i] = [pos_i, x_i].
For query i, we first set nums[pos_i] equal to x_i, 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 10^9 + 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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,1], queries = [[1,10],[3,5]]
›
Output:
26
💡 Note:
Query [1,10]: nums=[1,10,3,1]. DP: dp[0]=1, dp[1]=10, dp[2]=max(10,1+3)=10, dp[3]=max(10,10+1)=11. Query [3,5]: nums=[1,10,3,5]. DP: dp[0]=1, dp[1]=10, dp[2]=10, dp[3]=max(10,10+5)=15. Total=11+15=26
Example 2 — Single Element
$
Input:
nums = [5], queries = [[0,2],[0,7]]
›
Output:
9
💡 Note:
After query [0,2]: nums = [2], max sum = 2. After query [0,7]: nums = [7], max sum = 7. Total = 2 + 7 = 9.
Example 3 — All Negative
$
Input:
nums = [-1,-2], queries = [[0,1],[1,3]]
›
Output:
4
💡 Note:
After query [0,1]: nums = [1,-2], max sum = 1 (take first element). After query [1,3]: nums = [1,3], max sum = 3 (take second element, as taking both would violate adjacency). Actually max sum = max(1,3) = 3. Wait, let me recalculate. For [1,3]: we can't take both since they're adjacent. So max sum = max(1,3) = 3. Total = 1 + 3 = 4.
Constraints
- 1 ≤ nums.length ≤ 5 × 104
- 1 ≤ queries.length ≤ 5 × 104
- -105 ≤ nums[i] ≤ 105
- 0 ≤ posi < nums.length
- -105 ≤ xi ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code