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 109 + 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-108 <= nums[i] <= 108 2 <= k <= nThis approach leverages dynamic programming to break down the problem into subproblems, solving and combining them to build the solution.
The solution uses a dynamic programming technique to compute the maximum sum subarray. We maintain a dp array where dp[i] stores the maximum sum ending at index i. This helps to avoid recomputation and results in an optimal solution.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n)
Kadane's algorithm offers an optimized way to solve the maximum subarray problem using only a constant amount of space.
This C solution uses Kadane's algorithm to efficiently find the maximum sum subarray. It iteratively calculates the current local maximum and updates the global maximum if the local maximum exceeds it.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Approach 1: Dynamic Programming | Time Complexity: O(n) |
| Approach 2: Kadane's Algorithm | Time Complexity: O(n) |
L6. Recursion on Subsequences | Printing Subsequences • take U forward • 747,428 views views
Watch 9 more video solutions →Practice Find the Sum of Subsequence Powers with our built-in code editor and test cases.
Practice on FleetCode