You are given an integer array nums of length n.
For every positive integer g, we define the beauty of g as the product of g and the number of strictly increasing subsequences of nums whose greatest common divisor (GCD) is exactly g.
Return the sum of beauty values for all positive integers g.
Since the answer could be very large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3]
Output: 10
Explanation:
All strictly increasing subsequences and their GCDs are:
| Subsequence | GCD |
|---|---|
| [1] | 1 |
| [2] | 2 |
| [3] | 3 |
| [1,2] | 1 |
| [1,3] | 1 |
| [2,3] | 1 |
| [1,2,3] | 1 |
Calculating beauty for each GCD:
| GCD | Count of subsequences | Beauty (GCD × Count) |
|---|---|---|
| 1 | 5 | 1 × 5 = 5 |
| 2 | 1 | 2 × 1 = 2 |
| 3 | 1 | 3 × 1 = 3 |
Total beauty is 5 + 2 + 3 = 10.
Example 2:
Input: nums = [4,6]
Output: 12
Explanation:
All strictly increasing subsequences and their GCDs are:
| Subsequence | GCD |
|---|---|
| [4] | 4 |
| [6] | 6 |
| [4,6] | 2 |
Calculating beauty for each GCD:
| GCD | Count of subsequences | Beauty (GCD × Count) |
|---|---|---|
| 2 | 1 | 2 × 1 = 2 |
| 4 | 1 | 4 × 1 = 4 |
| 6 | 1 | 6 × 1 = 6 |
Total beauty is 2 + 4 + 6 = 12.
Constraints:
1 <= n == nums.length <= 1041 <= nums[i] <= 7 * 104When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
This problem computes the sum of beauty across all possible greatest common divisors of strictly increasing subsequences. For each integer, we first calculate the total number of strictly increasing subsequences consisting only of its multiples. Finally, we apply Mobius inversion or backward subtraction to find the exact number of subsequences for each greatest common divisor and accumulate their beauty.
Here's how the algorithm would work step-by-step:
def sum_of_beautiful_subsequences(nums):
MOD = 10**9 + 7
max_val = max(nums)
# Store indices for each distinct value in the array
positions_by_val = {}
for index, val in enumerate(nums):
if val not in positions_by_val:
positions_by_val[val] = []
positions_by_val[val].append(index)
counts_multiple = [0] * (max_val + 1)
# Count strictly increasing subsequences whose elements are multiples of each candidate divisor
for divisor in range(1, max_val + 1):
multiples = []
for multiple in range(divisor, max_val + 1, divisor):
if multiple in positions_by_val:
multiples.append(multiple)
if not multiples:
continue
items = []
for multiple in multiples:
for index in positions_by_val[multiple]:
items.append((index, multiple))
items.sort(key=lambda pair: pair[0])
bit = {}
total_for_divisor = 0
for _, multiple in items:
val_query = multiple - 1
sub_sum = 0
curr_idx = val_query
while curr_idx > 0:
if curr_idx in bit:
sub_sum = (sub_sum + bit[curr_idx]) % MOD
curr_idx -= curr_idx & (-curr_idx)
ways_ending_here = (sub_sum + 1) % MOD
total_for_divisor = (total_for_divisor + ways_ending_here) % MOD
curr_update = multiple
while curr_update <= max_val:
bit[curr_update] = (bit.get(curr_update, 0) + ways_ending_here) % MOD
curr_update += curr_update & (-curr_update)
counts_multiple[divisor] = total_for_divisor
# Use inclusion-exclusion to obtain the exact count for each greatest common divisor
exact_counts = [0] * (max_val + 1)
total_beauty = 0
for divisor in range(max_val, 0, -1):
current_count = counts_multiple[divisor]
for multiple in range(2 * divisor, max_val + 1, divisor):
current_count = (current_count - exact_counts[multiple]) % MOD
exact_counts[divisor] = current_count
total_beauty = (total_beauty + divisor * current_count) % MOD
return (total_beauty % MOD + MOD) % MOD
The problem asks for the sum of beauty values over all possible GCDs of strictly increasing subsequences. We can first compute the number of strictly increasing subsequences composed exclusively of multiples of each candidate divisor. Finally, we use Möbius inversion or backward inclusion-exclusion to isolate the counts for exact GCDs and compute the total beauty.
Here's how the algorithm would work step-by-step:
def sum_of_beautiful_subsequences(nums: list[int]) -> int:
modulo = 10**9 + 7
max_val = max(nums)
# Map each value to its indices in nums
value_to_indices = [[] for _ in range(max_val + 1)]
for index, val in enumerate(nums):
value_to_indices[val].append(index)
subseq_count_multiple = [0] * (max_val + 1)
# Calculate number of strictly increasing subsequences whose elements are multiples of g
for divisor in range(1, max_val + 1):
multiples_indices = []
for multiple in range(divisor, max_val + 1, divisor):
for idx in value_to_indices[multiple]:
multiples_indices.append((idx, multiple))
if not multiples_indices:
continue
multiples_indices.sort(key=lambda pair: pair[0])
unique_vals = sorted(list(set(multiple for idx, multiple in multiples_indices)))
val_to_rank = {val: rank + 1 for rank, val in enumerate(unique_vals)}
fenwick_tree = [0] * (len(unique_vals) + 1)
def query(idx_rank):
total = 0
curr = idx_rank
while curr > 0:
total = (total + fenwick_tree[curr]) % modulo
curr -= curr & -curr
return total
def update(idx_rank, delta):
curr = idx_rank
while curr < len(fenwick_tree):
fenwick_tree[curr] = (fenwick_tree[curr] + delta) % modulo
curr += curr & -curr
# Count increasing subsequences using a Fenwick tree
total_subsequences = 0
for idx, val in multiples_indices:
rank = val_to_rank[val]
count_smaller = query(rank - 1)
new_subsequences = (count_smaller + 1) % modulo
update(rank, new_subsequences)
total_subsequences = (total_subsequences + new_subsequences) % modulo
subseq_count_multiple[divisor] = total_subsequences
exact_gcd_count = [0] * (max_val + 1)
total_beauty = 0
# Use inclusion-exclusion to find exact GCD counts and accumulate beauty
for divisor in range(max_val, 0, -1):
count = subseq_count_multiple[divisor]
for multiple in range(2 * divisor, max_val + 1, divisor):
count = (count - exact_gcd_count[multiple]) % modulo
exact_gcd_count[divisor] = count
total_beauty = (total_beauty + divisor * count) % modulo
return (total_beauty % modulo + modulo) % modulo
| Case | How to Handle |
|---|---|
| Array length is less than k | Return a sum of zero since no valid subsequence can meet the minimum length requirement. |
| Array contains duplicate values | Strictly increasing condition naturally prevents selecting equal elements in a valid subsequence. |
| Array contains negative numbers and zeros | Comparison logic handles signs correctly as long as elements remain strictly greater than the previous. |
| No strictly increasing subsequence of length k exists | Return zero as the final accumulated sum since no valid subsequences are found. |
| Maximum possible inputs and large subset combinations | Use dynamic programming with coordinate compression or Fenwick trees to optimize performance and prevent timeouts. |
| Integer overflow during sum accumulation | Use 64-bit integers or modulo arithmetic if specified to accommodate extremely large sums. |
| Array is already strictly sorted in ascending order | All possible subsequences of length at least k are valid and must be counted efficiently. |