TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.43K subscribers
Post #1422 842
Задача: 1498. Number of Subsequences That Satisfy the Given Sum Condition
Сложность: medium

Вам дан массив целых чисел nums и целое число target.

Верните количество непустых подпоследовательностей массива nums, таких что сумма минимального и максимального элемента в них меньше или равна target. Так как ответ может быть слишком большим, верните его по модулю 10^9 + 7.

Пример:
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)


👨‍💻 Алгоритм:

1⃣Инициализация и подготовка:
Инициализируйте переменные answer равным 0 и n как длину массива nums.
Отсортируйте массив nums.
Подготовьте массив power для хранения степеней двойки до n по модулю 10^9+7.

2⃣Итерация и бинарный поиск:
Для каждого индекса left от 0 до n - 1 выполните бинарный поиск, чтобы найти самый правый индекс right, где nums[right] <= target - nums[left].
Если left <= right, добавьте количество допустимых подпоследовательностей к answer.

3⃣Возврат результата:
Верните answer по модулю 10^9+7.

😎 Решение:
class Solution {
public static int binarySearchRightmost(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}

public int numSubseq(int[] nums, int target) {
int n = nums.length;
int mod = 1_000_000_007;
Arrays.sort(nums);

int[] power = new int[n];
power[0] = 1;
for (int i = 1; i < n; ++i) {
power[i] = (power[i - 1] * 2) % mod;
}

int answer = 0;

for (int left = 0; left < n; left++) {
int right = binarySearchRightmost(nums, target - nums[left]) - 1;
if (right >= left) {
answer += power[right - left];
answer %= mod;
}
}
return answer;
}
}


Ставь 👍 и забирай 📚 Базу знаний
  • 👍 3
More from @easy_java_task
  1. Oct 17, 2026Post #2303
  2. Oct 17, 2026Задача: 1431. Kids With the Greatest Number of Candies Сложность: easy Дано n детей с конф…
  3. Oct 16, 2026Задача: 735. Asteroid Collision Сложность: medium Нам дан массив asteroids, состоящий из ц…
  4. Oct 16, 2026Post #2300
  5. Oct 15, 2026Задача: 229. Majority Element II Сложность: medium Дан массив целых чисел размера n, найди…
  6. Oct 14, 2026Задача: 1332. Remove Palindromic Subsequences Сложность: easy Вам дана строка s, состоящая…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →