首页 > 其他 > 详细

1498. Number of Subsequences That Satisfy the Given Sum Condition

时间:2021-03-03 08:32:39      阅读:32      评论:0      收藏:0      [点我收藏+]

Given an array of integers nums and an integer target.

Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.

 

Example 1:

Input: nums = [3,5,6,7], target = 9
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)

Example 2:

Input: nums = [3,3,6,8], target = 10
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]

Example 3:

Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
Explanation: There are 63 non-empty subsequences, two of them don‘t satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).

Example 4:

Input: nums = [5,2,4,1,7,6,8], target = 16
Output: 127
Explanation: All non-empty subset satisfy the condition (2^7 - 1) = 127

思路:
因为这题要求在一个subsquence里面min + max <= target, 所以我们要知道谁是min和max,这里就想到需要sort array. 然后最左边的就是min, 最右边的就是max,如果 min + max > target, 我们只能把max往左移动。如果min + max <= target, 那么就说明从min 到 max,所有的组合
都是符合要求的(必须包含min)。如果不包含min, 那么得到的结果有可能那个序列里面的 min + max 会超过targert. 如果里面有n个数(除了min),那么所有组合的可能就是 2^n.
 1 class Solution {
 2     public int numSubseq(int[] nums, int target) {
 3         Arrays.sort(nums);
 4         int ans = 0, n = nums.length, mod = (int)(1e9 + 7);
 5         int[] pows = new int[n];
 6         pows[0] = 1;
 7         for (int i = 1; i < n; i++) {
 8             pows[i] = (pows[i - 1] * 2) % mod;
 9         }
10         int i = 0, j = n - 1;
11         while (i <= j) {
12             if (nums[i] + nums[j] <= target) {
13                 ans = (ans + pows[j - i]) % mod;
14                 i++;
15             } else {
16                 j--;
17             }
18         }
19         return ans;
20     }
21 }

 

1498. Number of Subsequences That Satisfy the Given Sum Condition

原文:https://www.cnblogs.com/beiyeqingteng/p/14472226.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!