aboutsummaryrefslogtreecommitdiff
path: root/num_subseq_satisfy.c
diff options
context:
space:
mode:
Diffstat (limited to 'num_subseq_satisfy.c')
-rw-r--r--num_subseq_satisfy.c58
1 files changed, 21 insertions, 37 deletions
diff --git a/num_subseq_satisfy.c b/num_subseq_satisfy.c
index d7570d0..a007b28 100644
--- a/num_subseq_satisfy.c
+++ b/num_subseq_satisfy.c
@@ -1,6 +1,5 @@
// 1498. Number of Subsequences That Satisfy the Given Sum Condition
-#include <stdio.h>
-#include <stdlib.h>
+#include "leetcode.h"
/*
* given an array of integers 'nums' and an integer 'target'
@@ -9,47 +8,32 @@
* less or equal to 'target'. return modulo 10^9+7
*/
-#define MOD 1000000007
-
int cmp(const void *a, const void *b) { return *(int *)a - *(int *)b; }
-long long _pow(long long a, int b) {
- a %= MOD;
- if (!b)
- return 1;
- if (b)
- return a;
- if (b % 2)
- return a * _pow(a, b - 1) % MOD;
- return _pow(a * a, b / 2) % MOD;
-}
-
-int numSubseq(int *nums, int nums_size, int target) {
- int n = nums_size;
- qsort(nums, n, sizeof(int), cmp);
- long long ans;
- int j = n - 1;
- for (int i = 0; i < n; i++) {
- if (nums[i] * 2 > target)
- break;
- int rem = target - nums[i];
- while (i < j) {
- if (nums[j] > rem)
- j--;
- else
- break;
+int numSubseq(int *nums, int numsSize, int target) {
+ qsort(nums, numsSize, sizeof(int), cmp);
+ int ans = 0, l = 0, r = numsSize - 1, mod = 1e9 + 7;
+ int *pows = (int *)malloc(numsSize * sizeof(int));
+ pows[0] = 1;
+ for (int i = 1; i < numsSize; ++i)
+ pows[i] = (pows[i - 1] << 1) % mod;
+ while (l <= r) {
+ if (nums[l] + nums[r] > target) {
+ --r;
+ continue;
}
- ans += _pow(2, j - i);
- ans %= MOD;
+ ans = (ans + pows[r - l]) % mod;
+ ++l;
}
+ free(pows);
return ans;
}
int main() {
- int n1[] = {3, 5, 6, 7}, ns1 = 4, t1 = 9;
- int n2[] = {3, 3, 6, 8}, ns2 = 4, t2 = 10;
- int n3[] = {2, 3, 3, 4, 6, 7}, ns3 = 6, t3 = 12;
- printf("%d\n", numSubseq(n1, ns1, t1)); // expect: 4
- printf("%d\n", numSubseq(n2, ns2, t2)); // expect: 6
- printf("%d\n", numSubseq(n3, ns3, t3)); // expect: 61
+ int n1[] = {3, 5, 6, 7};
+ int n2[] = {3, 3, 6, 8};
+ int n3[] = {2, 3, 3, 4, 6, 7};
+ printf("%d\n", numSubseq(n1, ARRAY_SIZE(n1), 9)); // expect: 4
+ printf("%d\n", numSubseq(n2, ARRAY_SIZE(n2), 10)); // expect: 6
+ printf("%d\n", numSubseq(n3, ARRAY_SIZE(n3), 12)); // expect: 61
}