| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.NumberOfSubsequencesThatSatisfyTheGivenSumCondition; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class NumberOfSubsequencesThatSatisfyTheGivenSumConditionSortingTwoPointers : |
| | 16 | | INumberOfSubsequencesThatSatisfyTheGivenSumCondition |
| | 17 | | { |
| | 18 | | private const int Modulo = 1_000_000_007; |
| | 19 | |
|
| | 20 | | /// <summary> |
| | 21 | | /// Time complexity - O(n log n) |
| | 22 | | /// Space complexity - O(n) |
| | 23 | | /// </summary> |
| | 24 | | /// <param name="nums"></param> |
| | 25 | | /// <param name="target"></param> |
| | 26 | | /// <returns></returns> |
| | 27 | | public int NumSubseq(int[] nums, int target) |
| 3 | 28 | | { |
| 3 | 29 | | Array.Sort(nums); |
| | 30 | |
|
| 3 | 31 | | var powersOfTwo = new int[nums.Length]; |
| | 32 | |
|
| 3 | 33 | | powersOfTwo[0] = 1; |
| | 34 | |
|
| 28 | 35 | | for (var i = 1; i < nums.Length; i++) |
| 11 | 36 | | { |
| 11 | 37 | | powersOfTwo[i] = powersOfTwo[i - 1] * 2 % Modulo; |
| 11 | 38 | | } |
| | 39 | |
|
| 3 | 40 | | var result = 0; |
| | 41 | |
|
| 3 | 42 | | var left = 0; |
| 3 | 43 | | var right = nums.Length - 1; |
| | 44 | |
|
| 17 | 45 | | while (left <= right) |
| 14 | 46 | | { |
| 14 | 47 | | if (nums[left] + nums[right] <= target) |
| 8 | 48 | | { |
| 8 | 49 | | result = (result + powersOfTwo[right - left]) % Modulo; |
| | 50 | |
|
| 8 | 51 | | left++; |
| 8 | 52 | | } |
| | 53 | | else |
| 6 | 54 | | { |
| 6 | 55 | | right--; |
| 6 | 56 | | } |
| 14 | 57 | | } |
| | 58 | |
|
| 3 | 59 | | return result; |
| 3 | 60 | | } |
| | 61 | | } |