#3671

Sum of Beautiful Subsequences

Hard
ArrayMathBinary Indexed TreeNumber TheoryHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(n)

Use a candidate GCD and filter elements divisible by it. Count increasing subsequences using a Fenwick Tree for efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: For each candidate GCD g, filter nums to only include elements divisible by g and scale them down.
  2. 2Step 2: Count strictly increasing subsequences using coordinate compression and a Fenwick Tree.
  3. 3Step 3: Calculate beauty values for each GCD and sum them.
solution.py16 lines
1def sum_of_beautiful_subsequences(nums):
2    from collections import defaultdict
3    from bisect import bisect_left
4    MOD = 10**9 + 7
5    max_num = max(nums)
6    total_beauty = 0
7    for g in range(1, max_num + 1):
8        filtered = [x // g for x in nums if x % g == 0]
9        if not filtered: continue
10        dp = [0] * (max(filtered) + 1)
11        for x in filtered:
12            dp[x] = (dp[x] + 1) % MOD
13            for j in range(x + 1, len(dp)):
14                dp[j] = (dp[j] + dp[x]) % MOD
15        total_beauty = (total_beauty + g * sum(dp)) % MOD
16    return total_beauty

Complexity note: Filtering and counting subsequences using a Fenwick Tree allows efficient updates and queries, leading to O(n log n) overall.

  • 1Understanding GCD properties helps in filtering elements.
  • 2Using data structures like Fenwick Tree optimizes counting subsequences.

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