Leetcode algorithm series _0891_ The sum of the width of the subsequence
Title Description
Given an integer array A, consider all non-empty sequences of a.
For any sequence s, the width of S is the difference between the largest and smallest elements of S.
Returns the sum of the widths of all the sub-sequences of a.
Since the answer can be very large, please return to the answer modulo 10^9+7.
Example 1:
输入:[2,1,3]输出:6解释:子序列为 [1],[2],[3],[2,1],[2,3],[1,3],[2,1,3] 。相应的宽度是 0,0,0,1,1,2,2 。这些宽度之和是 6 。
Tips:
- 1 <= a.length <= 20000
- 1 <= a[i] <= 20000
Algorithm
const mod = 1e9 + 7func sumSubseqWidths(a []int) int { //[3,2,4,1] 和 排序后的 [1,2,3,4] 宽度之和相同 sort.Ints(a) n := len(a) res := 0 /** 作为最大值出现的次数 a[0] a[1] a[2] 1 2 4 [2,1,3],3作为最大值进行排列组合 [2,3],[1,3][,2,1,3],[3] */ times := 1 for i := 0; i < n; i++ { //a[i]作为最大值出现的次数==a[n-1-i]作为最小值出现的次数 res += (a[i] - a[n-1-i]) * times //res可能非常大,所以取模 res %= mod //times可能非常大,取模 times = (times << 1) % mod } return res}
Personal ideas
- A subsequence is a subset of array elements that are arranged to form several arrays, the maximum value in the array-the minimum value that is the subarray width
- [3,2,4,1] and [1,2,3,4] have different sub-sequences, but the sum of the width of the subsequence is the same
- Sort an array, and the width of a subsequence is the difference between the tail and the elements
- Example: Array [1,2,3,4], each element may be the maximum value of a subsequence, the minimum value, n is the length of the array
- A[i] As the maximum value, there are I elements smaller than it, can form a 2^i sub-sequence
- A[i] As a minimum, there are n-1-i elements larger than it, which can form a 2^ (n-1-i) sub-sequence
- Rule: a[0] as the maximum number of subsequence ==a[n-1] as the minimum number of sub-series, the same a[1] and a[n-1-1] ..., that is, a[i] the minimum number of times equal to A[n-1-i]
- Sum of the subsequence width = (max a[i]2^i+ ...) -(minimum value a[n-1-i]2^i ...)
- The sum of the subsequence width = (a[i]-a[n-1-i]*2^i) + ...
- The value of 2^i, which in turn is 1,2,4,8 ...., it will be large, so you need to take a model of 10^9+7
Summarize
- Solve the problem, always find out the mathematical law behind the problem
GitHub
- Project Source is here
- The author will always maintain the project, solve the algorithm problem in Leetcode, and write down his own ideas and opinions, and devote to the algorithm that everyone can understand.
Personal public number
- Favorite friends can pay attention to, thank you for your support
- Record the learning and life of the farmers in the code