This repository has been archived by the owner on Jun 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1057 from osama-swe/main
Added my sol to 6 May
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
...dition/06- Number of Subsequences That Satisfy the Given Sum Condition (Osama Ayman).java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// Author: Osama Ayman | ||
// Time: O(nlogn) | ||
// Space: O(n) | ||
class Solution { | ||
|
||
public int numSubseq(int[] nums, int target) { | ||
int mod = (int) 1e9+7; | ||
// Sort the array and apply the 2-pointers strategy | ||
Arrays.sort(nums); | ||
int n = nums.length; | ||
// Precompute the value of 2 to the power of each value. | ||
int[] power = new int[n]; | ||
power[0] = 1; | ||
for (int i = 1; i < n; ++i) { | ||
power[i] = (power[i - 1] * 2) % mod; | ||
} | ||
|
||
int left = 0; | ||
int right = nums.length-1; | ||
int res = 0; | ||
while(left <= right){ | ||
if(nums[left] + nums[right] <= target){ | ||
// the number of subsequences is 2 ^ (right-left) | ||
res += power[right - left]; | ||
res %= mod; | ||
left++; | ||
} | ||
else right--; | ||
} | ||
return res; | ||
} | ||
} |