[LeetCode] 891. Sum of Subsequence Widths

The width of a sequence is the difference between the maximum and minimum elements in the sequence.

Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

Example 1:

Input: nums = [2,1,3]
Output: 6
Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.

Example 2:

Input: nums = [2]
Output: 0

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105

子序列宽度之和。

一个序列的 宽度 定义为该序列中最大元素和最小元素的差值。
给你一个整数数组 nums ,返回 nums 的所有非空 子序列 的 宽度之和 。由于答案可能非常大,请返回对 109 + 7 取余 后的结果。
子序列 定义为从一个数组里删除一些(或者不删除)元素,但不改变剩下元素的顺序得到的数组。例如,[3,6,2,7] 就是数组 [0,3,1,6,2,2,7] 的一个子序列。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sum-of-subsequence-widths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道hard题,但是如果你对数学很敏感,感觉也不是很难。我参考了这个帖子,总结的很详细。

因为题目请你找的是子序列,所以顺序就并不是那么重要。问题的关键在于你如何确定某个数字 nums[i] 是多少个子序列的最大值/最小值,从而确定这个数字 nums[i] 的贡献值。其余部分参见引用贴,写的真的很好。

时间O(nlogn) - sort

空间O(n)

Java实现

复制代码
 1 class Solution {
 2     public int sumSubseqWidths(int[] nums) {
 3         Arrays.sort(nums);
 4         int MOD = (int) Math.pow(10, 9) + 7;
 5         int len = nums.length;
 6         long res = 0;
 7         long[] pow = new long[len];
 8         pow[0] = 1;
 9         for (int i = 1; i < len; i++) {
10             pow[i] = (pow[i - 1] << 1) % MOD;
11         }
12 
13         for (int i = 0; i < len; i++) {
14             res = (res + (pow[i] - pow[len - i - 1]) * nums[i] % MOD) % MOD;
15         }
16         return (int) res;
17     }
18 }
复制代码

 

LeetCode 题目总结

posted @   CNoodle  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2020-11-19 [LeetCode] 725. Split Linked List in Parts
点击右上角即可分享
微信分享提示