#3351

Sum of Good Subsequences

Hard
ArrayHash TableDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + k), where k is the range of numbers (up to 100000)
Space
O(1)
O(k)
💡

Intuition

Time O(n + k), where k is the range of numbers (up to 100000)Space O(k)

The optimal solution uses dynamic programming to count how many times each element can appear in good subsequences. We track the sum of subsequences ending with each number and build upon previous results.

⚙️

Algorithm

5 steps
  1. 1Step 1: Count the frequency of each number in the array.
  2. 2Step 2: Initialize a DP array to store the sum of good subsequences for each number.
  3. 3Step 3: Iterate through the unique numbers and calculate the sum of good subsequences based on the previous number's results.
  4. 4Step 4: For each number, update the DP array using the frequency of the current number and the previous number.
  5. 5Step 5: Return the total sum from the DP array modulo 10^9 + 7.
solution.py14 lines
1# Full working Python code
2from collections import Counter
3
4def sum_good_subsequences(nums):
5    MOD = 10**9 + 7
6    count = Counter(nums)
7    dp = {}  # dp[number] = sum of good subsequences ending with 'number'
8    total_sum = 0
9
10    for num in sorted(count.keys()):
11        dp[num] = (num * count[num] + (dp.get(num - 1, 0) * count[num]) % MOD) % MOD
12        total_sum = (total_sum + dp[num]) % MOD
13
14    return total_sum

Complexity note: The time complexity is linear with respect to the input size plus the range of numbers, making it efficient for large inputs.

  • 1Counting occurrences of each number helps in calculating contributions to subsequences efficiently.
  • 2Dynamic programming allows us to build upon previous results, avoiding redundant calculations.

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