#3165

Maximum Sum of Subsequence With Non-adjacent Elements

Hard
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
Unknown
Space
O(1)
Unknown
💡

Intuition

Time UnknownSpace Unknown

The optimal approach uses dynamic programming to calculate the maximum sum of non-adjacent elements efficiently. We maintain a running total of the maximum sums while updating the array based on queries.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two variables, prev1 and prev2, to keep track of the maximum sums including and excluding the current element.
  2. 2Step 2: For each query, update the specified position in the nums array.
  3. 3Step 3: Iterate through the updated nums array, updating prev1 and prev2 based on the current element's value.
  4. 4Step 4: After processing the entire array, the maximum sum is stored in prev1.
  5. 5Step 5: Return the sum of maximum sums for all queries.
solution.py14 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def max_sum_subsequence(nums, queries):
5    total_sum = 0
6    for pos, x in queries:
7        nums[pos] = x
8        prev1, prev2 = 0, 0
9        for num in nums:
10            new_prev1 = max(prev1, prev2 + num)
11            prev2 = prev1
12            prev1 = new_prev1
13        total_sum = (total_sum + prev1) % MOD
14    return total_sum

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.