Find the Sum of Subsequence Powers Problem
Description
LeetCode Problem 3098.
You are given an integer array nums of length n, and a positive integer k.
The power of a subsequence is defined as the minimum absolute difference between any two elements in the subsequence.
Return the sum of powers of all subsequences of nums which have length equal to k.
Since the answer may be large, return it modulo 10^9+ 7.
Example 1:
Input: nums = [1,2,3,4], k = 3
Output: 4
Explanation:
There are 4 subsequences in nums which have length 3: [1,2,3], [1,3,4], [1,2,4], and [2,3,4]. The sum of powers is |2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4.
Example 2:
Input: nums = [2,2], k = 2
Output: 0
Explanation:
The only subsequence in nums which has length 2 is [2,2]. The sum of powers is |2 - 2| = 0.
Example 3:
Input: nums = [4,3,-1], k = 2
Output: 10
Explanation:
There are 3 subsequences in nums which have length 2: [4,3], [4,-1], and [3,-1]. The sum of powers is |4 - 3| + |4 - (-1)| + |3 - (-1)| = 10.
Constraints:
2 <= n == nums.length <= 50-10^8 <= nums[i] <= 10^82 <= k <= n
Solution
Approach: Memoized Search over a Sorted Array
After sorting, the minimum difference between elements of a subsequence is the minimum difference between neighbours that were picked. Define dfs(i, j, k, mi): we are looking at index i, the last picked element is j (n means none yet), k more elements are needed, and the smallest gap so far is mi.
- If
i >= n, returnmiwhenk = 0, otherwise0. - If fewer than
kelements remain, return0. - Otherwise add the results of skipping
i, and of pickingi(the new gap ismin(mi, nums[i] - nums[j]), or unchanged when nothing was picked before).
Everything is taken modulo 10^9 + 7, and results are memoized on (i, j, k, mi).
Complexity: O(n^4 k) time and space.
from functools import lru_cache
from math import inf
class Solution:
def sumOfPowers(self, nums: List[int], k: int) -> int:
@lru_cache(None)
def dfs(i: int, j: int, k: int, mi: int) -> int:
if i >= n:
return mi if k == 0 else 0
if n - i < k:
return 0
ans = dfs(i + 1, j, k, mi)
if j == n:
ans += dfs(i + 1, i, k - 1, mi)
else:
ans += dfs(i + 1, i, k - 1, min(mi, nums[i] - nums[j]))
ans %= mod
return ans
mod = 10**9 + 7
n = len(nums)
nums.sort()
return dfs(0, n, k, inf)