From d037d0ee264d2a6f907f754a1831494c779c8bf4 Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Wed, 21 Oct 2026 00:07:35 +0700 Subject: [PATCH 01/19] Added tasks 3946-3968 --- .../Solution.java | 60 +++++ .../readme.md | 48 ++++ .../Solution.java | 60 +++++ .../readme.md | 52 +++++ .../Solution.java | 58 +++++ .../readme.md | 56 +++++ .../Solution.java | 17 ++ .../readme.md | 33 +++ .../Solution.java | 26 +++ .../readme.md | 60 +++++ .../Solution.java | 21 ++ .../readme.md | 57 +++++ .../Solution.java | 144 ++++++++++++ .../readme.md | 68 ++++++ .../Solution.java | 21 ++ .../readme.md | 48 ++++ .../Solution.java | 36 +++ .../readme.md | 51 +++++ .../Solution.java | 62 +++++ .../readme.md | 67 ++++++ .../Solution.java | 119 ++++++++++ .../readme.md | 67 ++++++ .../s3959_check_good_integer/Solution.java | 16 ++ .../s3959_check_good_integer/readme.md | 41 ++++ .../Solution.java | 39 ++++ .../readme.md | 51 +++++ .../Solution.java | 41 ++++ .../readme.md | 65 ++++++ .../Solution.java | 211 ++++++++++++++++++ .../readme.md | 50 +++++ .../Solution.java | 19 ++ .../readme.md | 58 +++++ .../Solution.java | 29 +++ .../readme.md | 48 ++++ .../Solution.java | 47 ++++ .../readme.md | 43 ++++ .../Solution.java | 14 ++ .../readme.md | 53 +++++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 25 +++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 18 ++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 18 ++ .../SolutionTest.java | 21 ++ .../SolutionTest.java | 28 +++ .../SolutionTest.java | 28 +++ .../SolutionTest.java | 18 ++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 23 ++ .../SolutionTest.java | 18 ++ .../SolutionTest.java | 18 ++ .../SolutionTest.java | 18 ++ 57 files changed, 2473 insertions(+) create mode 100644 src/main/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/Solution.java create mode 100644 src/main/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/readme.md create mode 100644 src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/Solution.java create mode 100644 src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/readme.md create mode 100644 src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/Solution.java create mode 100644 src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/readme.md create mode 100644 src/main/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/Solution.java create mode 100644 src/main/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/readme.md create mode 100644 src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java create mode 100644 src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/readme.md create mode 100644 src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/Solution.java create mode 100644 src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/readme.md create mode 100644 src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/Solution.java create mode 100644 src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/readme.md create mode 100644 src/main/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/Solution.java create mode 100644 src/main/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/readme.md create mode 100644 src/main/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/Solution.java create mode 100644 src/main/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/readme.md create mode 100644 src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/Solution.java create mode 100644 src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/readme.md create mode 100644 src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java create mode 100644 src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/readme.md create mode 100644 src/main/java/g3901_4000/s3959_check_good_integer/Solution.java create mode 100644 src/main/java/g3901_4000/s3959_check_good_integer/readme.md create mode 100644 src/main/java/g3901_4000/s3960_frequency_balance_subarray/Solution.java create mode 100644 src/main/java/g3901_4000/s3960_frequency_balance_subarray/readme.md create mode 100644 src/main/java/g3901_4000/s3961_maximize_sum_of_device_ratings/Solution.java create mode 100644 src/main/java/g3901_4000/s3961_maximize_sum_of_device_ratings/readme.md create mode 100644 src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java create mode 100644 src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/readme.md create mode 100644 src/main/java/g3901_4000/s3963_create_grid_with_exactly_one_path/Solution.java create mode 100644 src/main/java/g3901_4000/s3963_create_grid_with_exactly_one_path/readme.md create mode 100644 src/main/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/Solution.java create mode 100644 src/main/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/readme.md create mode 100644 src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java create mode 100644 src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/readme.md create mode 100644 src/main/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/Solution.java create mode 100644 src/main/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/readme.md create mode 100644 src/test/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3948_lexicographically_maximum_mex_array/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3959_check_good_integer/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3960_frequency_balance_subarray/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3961_maximize_sum_of_device_ratings/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3963_create_grid_with_exactly_one_path/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3966_count_good_integers_in_a_range/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/SolutionTest.java diff --git a/src/main/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/Solution.java b/src/main/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/Solution.java new file mode 100644 index 000000000..8fd50d60a --- /dev/null +++ b/src/main/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/Solution.java @@ -0,0 +1,60 @@ +package g3901_4000.s3946_maximum_number_of_items_from_sale_i; + +// #Medium #Array #Dynamic_Programming #Greedy #Staff #Weekly_Contest_504 +// #2026_10_20_Time_13_ms_(100.00%)_Space_46.50_MB_(96.15%) + +public class Solution { + public int maximumSaleItems(int[][] items, int budget) { + int n = items.length; + int maxFactor = 0; + int minPrice = Integer.MAX_VALUE; + // Find the maximum factor (for our frequency array) and the minimum price + for (int[] item : items) { + maxFactor = Math.max(maxFactor, item[0]); + minPrice = Math.min(minPrice, item[1]); + } + // Count frequencies of each factor + int[] freq = new int[maxFactor + 1]; + for (int[] item : items) { + freq[item[0]]++; + } + // Precompute how many free items we get by buying at least 1 copy of item i + int[] free = new int[n]; + for (int i = 0; i < n; i++) { + int f = items[i][0]; + int count = 0; + // Sum up the frequencies of all multiples of factor f + for (int mult = f; mult <= maxFactor; mult += f) { + count += freq[mult]; + } + // Subtract 1 because we shouldn't count the item itself as a free copy + free[i] = count - 1; + } + // 0-1 Knapsack DP + // dp[c] stores the max items we can get by spending exactly 'c' budget to activate items + int[] dp = new int[budget + 1]; + java.util.Arrays.fill(dp, -1); + dp[0] = 0; + for (int i = 0; i < n; i++) { + int weight = items[i][1]; + int value = 1 + free[i]; + for (int c = budget; c >= weight; c--) { + if (dp[c - weight] != -1) { + dp[c] = Math.max(dp[c], dp[c - weight] + value); + } + } + } + // Evaluate the best combination of activated items + leftover budget spent on cheapest + // items + int maxTotal = 0; + for (int c = 0; c <= budget; c++) { + if (dp[c] != -1) { + // dp[c] gives us the activation items. + // We buy the cheapest item repeatedly with the remaining budget. + int currentTotal = dp[c] + (budget - c) / minPrice; + maxTotal = Math.max(maxTotal, currentTotal); + } + } + return maxTotal; + } +} diff --git a/src/main/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/readme.md b/src/main/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/readme.md new file mode 100644 index 000000000..b25879e7a --- /dev/null +++ b/src/main/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/readme.md @@ -0,0 +1,48 @@ +3946\. Maximum Number of Items From Sale I + +Medium + +You are given a 2D integer array `items`, where items[i] = [factori, pricei] represents the ith item. You are also given an integer `budget`. + +There are unlimited copies of each item available for purchase.You may buy any number of copies of any items such that the total cost of the purchased copies is at most `budget`. + +After buying items, you may receive free copies according to the following rules: + +* For each item `i` that you bought **at least one copy** of, you receive **one free copy** of every item `j` such that `j != i` and factori divides factorj. +* Buying multiple copies of the same item `i` does **not** give additional free copies through item `i`. +* The same item `j` can be received multiple times for free if it is received from purchases of different item types. + +Return the **maximum total number of item copies** you can obtain, including both purchased copies and free copies, while spending at most `budget` on purchased items. + +**Example 1:** + +**Input:** items = [[6,2],[2,6],[3,4]], budget = 9 + +**Output:** 4 + +**Explanation:** + +* You can buy 2 copies of item 0 and 1 copy of item 2 for a total cost of `2 * 2 + 4 = 8`, which is not greater than `budget = 9`. +* Buying item 2 gives 1 free copy of item 0, because factor2 = 3 divides factor0 = 6. +* You leave with 3 purchased copies and 1 free copy, for a total of 4 item copies. + +**Example 2:** + +**Input:** items = [[2,4],[3,2],[4,1],[6,4],[12,4]], budget = 8 + +**Output:** 10 + +**Explanation:** + +* You can buy 1 copy of item 0, 1 copy of item 1, and 2 copies of item 2 for a total cost of `4 + 2 + 2 * 1 = 8`. +* Buying item 0 gives 1 free copy of items 2, 3, and 4. +* Buying item 1 gives 1 free copy of items 3 and 4. +* Buying item 2 gives 1 free copy of item 4. +* Thus, you receive 6 free copies. You leave with 4 purchased copies and 6 free copies, for a total of 10 item copies. + +**Constraints:** + +* `1 <= items.length <= 1000` +* items[i] = [factori, pricei] +* 1 <= factori, pricei <= 1500 +* `1 <= budget <= 1500` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/Solution.java b/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/Solution.java new file mode 100644 index 000000000..b466f0582 --- /dev/null +++ b/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/Solution.java @@ -0,0 +1,60 @@ +package g3901_4000.s3947_maximum_number_of_items_from_sale_ii; + +// #Medium #Array #Sorting #Greedy #Heap_Priority_Queue #Staff #Weekly_Contest_504 +// #2026_10_20_Time_20_ms_(82.93%)_Space_231.68_MB_(87.81%) + +import java.util.Arrays; + +public class Solution { + public int maximumSaleItems(int[][] items, int budget) { + int n = items.length; + int[] count = new int[n + 1]; + long min = Long.MAX_VALUE; + for (int[] item : items) { + count[item[0]]++; + if (item[1] < min) { + min = item[1]; + } + } + + int[] temp = new int[n + 1]; + for (int i = 1; i <= n; i++) { + if (count[i] > 0) { + int m = -1; + for (int j = i; j <= n; j += i) { + m += count[j]; + } + temp[i] = m; + } + } + + long[] deal = new long[n]; + int dealcount = 0; + long limit = min * 2; + for (int[] item : items) { + int first = item[0]; + int second = item[1]; + if (second < limit) { + int m = temp[first]; + if (m > 0) { + deal[dealcount++] = ((long) second << 32) | (m & 0xFFFFFFFFL); + } + } + } + + Arrays.sort(deal, 0, dealcount); + long total = 0; + for (int i = 0; i < dealcount; i++) { + long deals = deal[i]; + int m = (int) (deals >>> 32); + int counts = (int) (deals & 0xFFFFFFFFL); + if (budget >= m) { + long time = Math.min((long) counts, budget / m); + budget = (int) (budget - (time * m)); + total += 2 * time; + } + } + total += budget / min; + return (int) total; + } +} diff --git a/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/readme.md b/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/readme.md new file mode 100644 index 000000000..9462eff79 --- /dev/null +++ b/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/readme.md @@ -0,0 +1,52 @@ +3947\. Maximum Number of Items From Sale II + +Medium + +You are given a 2D integer array `items`, where items[i] = [factori, pricei] represents the ith item. You are also given an integer `budget`. + +There are unlimited copies of each item available for purchase. You may buy any number of copies of any items such that the total cost of the purchased copies is at most `budget`. + +After buying items, you may receive free copies according to the following rules: + +* Each purchased copy of item `i` can give you **at most one** free copy of another item `j`. +* The free item must satisfy `i != j` and factori divides factorj. +* For each ordered pair `(i, j)`, you can receive a free copy of item `j` from purchases of item `i` **at most once**, regardless of how many copies of item `i` you buy. +* The same item `j` can be received multiple times for free if it is received from purchases of different item types. + +Return the **maximum total number of item copies** you can obtain, including both purchased copies and free copies, while spending at most `budget` on purchased items. + +**Example 1:** + +**Input:** items = [[1,6],[2,4],[3,5]], budget = 19 + +**Output:** 5 + +**Explanation:** + +* You can buy 2 copies of item 0 and 1 copy of item 1 for a total cost of `2 * 6 + 4 = 16`, which is not greater than `budget = 19`. +* One purchased copy of item 0 gives 1 free copy of item 1, because factor0 = 1 divides factor1 = 2. +* The other purchased copy of item 0 gives 1 free copy of item 2, because factor0 = 1 divides factor2 = 3. +* You leave with 3 purchased copies and 2 free copies, for a total of 5 item copies. + +**Example 2:** + +**Input:** items = [[2,8],[1,10],[6,6],[4,12],[5,20],[5,17]], budget = 35 + +**Output:** 7 + +**Explanation:** + +* You can buy 2 copies of item 0, 1 copy of item 1, and 1 copy of item 2 for a total cost of `2 * 8 + 10 + 6 = 32`, which is not greater than `budget = 35`. +* One purchased copy of item 0 gives 1 free copy of item 2, because factor0 = 2 divides factor2 = 6. +* The other purchased copy of item 0 gives 1 free copy of item 3, because factor0 = 2 divides factor3 = 4. +* The purchased copy of item 1 gives 1 free copy of item 2, because factor1 = 1 divides factor2 = 6. +* Buying item 2 gives no free copy, because factor2 = 6 does not divide the factor of any other item. +* You leave with 4 purchased copies and 3 free copies, for a total of 7 item copies. + +**Constraints:** + +* 1 <= items.length <= 105 +* items[i] = [factori, pricei] +* 1 <= factori <= items.length +* 1 <= pricei <= 109 +* 1 <= budget <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/Solution.java b/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/Solution.java new file mode 100644 index 000000000..3aa09ec9e --- /dev/null +++ b/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/Solution.java @@ -0,0 +1,58 @@ +package g3901_4000.s3948_lexicographically_maximum_mex_array; + +// #Hard #Array #Hash_Table #Greedy #Queue #Senior_Staff #Weekly_Contest_504 +// #2026_10_20_Time_4_ms_(100.00%)_Space_68.51_MB_(66.67%) + +public class Solution { + public int[] maximumMEX(int[] nums) { + int n = nums.length; + int[] suffixMex = new int[n]; + boolean[] seen = new boolean[n + 2]; + int currMex = 0; + + for (int i = n - 1; i >= 0; i--) { + if (nums[i] < n + 2) { + seen[nums[i]] = true; + } + while (seen[currMex]) { + currMex++; + } + suffixMex[i] = currMex; + } + + int[] result = new int[n]; + int resIdx = 0; + + int[] seenAtStep = new int[n + 2]; + int stepCounter = 0; + + int i = 0; + while (i < n) { + int m = suffixMex[i]; + result[resIdx++] = m; + + if (m == 0) { + i++; + } else { + stepCounter++; + int found = 0; + int j = i; + while (j < n) { + if (nums[j] < m && seenAtStep[nums[j]] != stepCounter) { + seenAtStep[nums[j]] = stepCounter; + found++; + } + if (found == m) { + i = j + 1; + break; + } + j++; + } + } + } + + int[] finalResult = new int[resIdx]; + System.arraycopy(result, 0, finalResult, 0, resIdx); + return finalResult; + } +} diff --git a/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/readme.md b/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/readme.md new file mode 100644 index 000000000..8c56a9156 --- /dev/null +++ b/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/readme.md @@ -0,0 +1,56 @@ +3948\. Lexicographically Maximum MEX Array + +Hard + +You are given an integer array `nums`. + +You want to construct an array `result` by repeatedly performing the following operation until `nums` becomes empty: + +* Choose an integer `k` such that `1 <= k <= len(nums)`. +* Compute the **MEX** of the first `k` elements of `nums`. +* Append this **MEX** to `result`. +* Remove the first `k` elements from `nums`. + +Return the **lexicographically maximum** array `result` that can be obtained after performing the operations. + +The **MEX** of an array is the **smallest non-negative** integer not present in the array. + +An array `a` is **lexicographically greater** than an array `b` if in the first position where `a` and `b` differ, array `a` has an element that is greater than the corresponding element in `b`. If the first `min(a.length, b.length)` elements do not differ, then the longer array is the **lexicographically greater** one. + +**Example 1:** + +**Input:** nums = [0,1,0] + +**Output:** [2,1] + +**Explanation:** + +* Take the first `k = 2` elements `[0, 1]` which has MEX = 2. Current `result = [2]`. +* Remaining array `[0]` has MEX = 1. Thus, the final `result = [2, 1]`. + +**Example 2:** + +**Input:** nums = [1,0,2] + +**Output:** [3] + +**Explanation:** + +* Take the first `k = 3` elements `[1, 0, 2]` which has MEX = 3. +* `nums` is now empty. Thus, the final `result = [3]`. + +**Example 3:** + +**Input:** nums = [3,1] + +**Output:** [0,0] + +**Explanation:** + +* Take `k = 1`, first element `[3]` has MEX = 0. Current `result = [0]`. +* Remaining array `[1]` has MEX = 0. Thus, the final `result = [0, 0]`. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/Solution.java b/src/main/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/Solution.java new file mode 100644 index 000000000..a920f5e50 --- /dev/null +++ b/src/main/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/Solution.java @@ -0,0 +1,17 @@ +package g3901_4000.s3950_exactly_one_consecutive_set_bits_pair; + +// #Easy #Bit_Manipulation #Mid_Level #Biweekly_Contest_184 +// #2026_10_20_Time_1_ms_(98.26%)_Space_42.21_MB_(89.58%) + +public class Solution { + public boolean consecutiveSetBits(int n) { + int cnt = 0; + while (n != 0) { + if ((n & 3) == 3) { + cnt++; + } + n = n >> 1; + } + return cnt == 1; + } +} diff --git a/src/main/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/readme.md b/src/main/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/readme.md new file mode 100644 index 000000000..444367c9a --- /dev/null +++ b/src/main/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/readme.md @@ -0,0 +1,33 @@ +3950\. Exactly One Consecutive Set Bits Pair + +Easy + +You are given an integer `n`. + +Return `true` if its binary representation contains **exactly one adjacent pair** of set bits, and `false` otherwise. + +**Example 1:** + +**Input:** n = 6 + +**Output:** true + +**Explanation:** + +* Binary representation of 6 is `110`. +* There is exactly one adjacent pair of set bits (`"11"`). Thus, the answer is `true`. + +**Example 2:** + +**Input:** n = 5 + +**Output:** false + +**Explanation:** + +* Binary representation of 5 is `101`. +* There is no adjacent pair of set bits. Thus, the answer is `false`. + +**Constraints:** + +* 0 <= n <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java b/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java new file mode 100644 index 000000000..00098239a --- /dev/null +++ b/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java @@ -0,0 +1,26 @@ +package g3901_4000.s3951_minimum_energy_to_maintain_brightness; + +// #Medium #Array #Sorting #Senior #Biweekly_Contest_184 +// #2026_10_20_Time_10_ms_(100.00%)_Space_189.60_MB_(91.67%) + +import java.util.Arrays; + +public class Solution { + public long minEnergy(int n, int brightness, int[][] intervals) { + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + int st = 0; + int ed = -1; + int tot = 0; + for (var a : intervals) { + if (a[0] <= ed) { + if (a[1] > ed) ed = a[1]; + } else { + tot += ed - st + 1; + st = a[0]; + ed = a[1]; + } + } + tot += ed - st + 1; + return (long) tot * ((brightness + 2) / 3); + } +} diff --git a/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/readme.md b/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/readme.md new file mode 100644 index 000000000..5a545d22b --- /dev/null +++ b/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/readme.md @@ -0,0 +1,60 @@ +3951\. Minimum Energy to Maintain Brightness + +Medium + +You are given an integer `n`, representing `n` light bulbs arranged in a line and indexed from 0 to `n - 1`. + +You are also given an integer `brightness` and a 2D integer array `intervals`, where intervals[i] = [starti, endi] represents an **inclusive** time interval during which the lighting requirement **must** be satisfied. + +At each time unit, every bulb can independently be either on or off. A bulb that is on **illuminates** its own position and its **adjacent** positions, if they exist. + +The **total illumination** at a time unit is the number of **illuminated** positions. Each position is counted **at most once**. + +For every integer time unit covered by **at least** one interval in `intervals`, the **total illumination** must be **at least** `brightness`. At time units not covered by any interval, all bulbs may remain off. Each bulb that is on consumes 1 unit of energy for that time unit. + +Return an integer denoting the **minimum** total energy required. + +**Example 1:** + +**Input:** n = 5, brightness = 5, intervals = [[6,12]] + +**Output:** 14 + +**Explanation:** + +* Turn on the light bulbs at positions 1 and 4. +* Current state of line: `0 1 0 0 1`. +* All 5 positions are illuminated, so the required brightness is reached. +* The active interval has length `12 - 6 + 1 = 7`, so the total energy is `2 * 7 = 14`. + +**Example 2:** + +**Input:** n = 2, brightness = 1, intervals = [[0,0],[2,2]] + +**Output:** 2 + +**Explanation:** + +* Turn on one light bulb during each active interval. +* Each interval has length 1, so the total active time is `1 + 1 = 2`. +* The total energy is `1 * 2 = 2`. + +**Example 3:** + +**Input:** n = 4, brightness = 2, intervals = [[1,3],[2,4]] + +**Output:** 4 + +**Explanation:** + +* Turn on one light bulb. It can illuminate at least 2 positions. +* The active intervals overlap, so the total active time is the length of `[1,4]`, which is 4. +* The total energy is `1 * 4 = 4`. + +**Constraints:** + +* 1 <= n <= 106 +* `1 <= brightness <= n` +* 1 <= intervals.length <= 105 +* intervals[i] == [starti, endi] +* 0 <= starti <= endi <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/Solution.java b/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/Solution.java new file mode 100644 index 000000000..62257ef53 --- /dev/null +++ b/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/Solution.java @@ -0,0 +1,21 @@ +package g3901_4000.s3952_maximum_total_value_of_covered_indices; + +// #Medium #Array #String #Dynamic_Programming #Greedy #Staff #Biweekly_Contest_184 +// #2026_10_20_Time_8_ms_(93.94%)_Space_127.68_MB_(89.39%) + +public class Solution { + public long maxTotal(int[] A, String s) { + int n = A.length; + int mn = 100000; + long res = 0; + for (int i = n - 1; i >= 0; --i) { + res += A[i]; + mn = Math.min(mn, A[i]); + if (s.charAt(i) == '0') { + res -= mn; + mn = 100000; + } + } + return res; + } +} diff --git a/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/readme.md b/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/readme.md new file mode 100644 index 000000000..20de8163c --- /dev/null +++ b/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/readme.md @@ -0,0 +1,57 @@ +3952\. Maximum Total Value of Covered Indices + +Medium + +You are given an integer array `nums` of length `n` and a binary string `s` of length `n`, where `s[i] == '1'` means index `i` initially contains a **token** and `s[i] == '0'` means it does not. + +You may perform the following operation any number of times: + +* Choose a token currently located at index `i`, where `i > 0`, such that this token has **not** been moved before. +* Move this token from index `i` to index `i - 1`. + +An index is considered **covered** if it contains a token after all moves. + +Return an integer denoting the **maximum total value** of `nums` at the covered indices after optimally performing the operations. + +**Example 1:** + +**Input:** nums = [9,2,6,1], s = "0101" + +**Output:** 15 + +**Explanation:** + +* Initially, indices 1 and 3 contain tokens. +* Move the token from index 3 to index 2. +* Move the token from index 1 to index 0. +* The covered indices are `[0, 2]`, so the total value is `nums[0] + nums[2] = 9 + 6 = 15`. + +**Example 2:** + +**Input:** nums = [5,1,4], s = "001" + +**Output:** 4 + +**Explanation:** + +* Initially, only index 2 contains a token. +* It is optimal to leave the token at index 2. +* The covered index is `[2]`, so the total value is `nums[2] = 4`. + +**Example 3:** + +**Input:** nums = [9,3,5], s = "011" + +**Output:** 14 + +**Explanation:** + +* Initially, indices 1 and 2 contain tokens. +* Move the token from index 1 to index 0. +* The covered indices are `[0, 2]`, so the total value is `nums[0] + nums[2] = 9 + 5 = 14`. + +**Constraints:** + +* 1 <= n == nums.length == s.length <= 105 +* 1 <= nums[i] <= 105 +* `s[i]` is either `'0'` or `'1'` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/Solution.java b/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/Solution.java new file mode 100644 index 000000000..67ebb9b30 --- /dev/null +++ b/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/Solution.java @@ -0,0 +1,144 @@ +package g3901_4000.s3953_maximum_score_with_co_prime_element; + +// #Hard #Array #Hash_Table #Math #Enumeration #Number_Theory #Combinatorics #Senior_Staff +// #Biweekly_Contest_184 #2026_10_20_Time_33_ms_(100.00%)_Space_86.44_MB_(96.88%) + +import java.util.ArrayList; +import java.util.List; + +public class Solution { + + public int maxScore(int[] nums, int maxVal) { + int max = findMax(nums, maxVal); + int[] cnt = countNumbers(nums, max); + int[] groupCnt = buildGroupCounts(cnt, max); + + int best = findBestAboveMaxVal(max, maxVal, cnt, groupCnt); + return findBestWithinMaxVal(maxVal, cnt, groupCnt, best); + } + + private int findMax(int[] nums, int maxVal) { + int max = maxVal; + for (int num : nums) { + if (num > max) { + max = num; + } + } + return max; + } + + private int[] countNumbers(int[] nums, int max) { + int[] cnt = new int[max + 1]; + for (int num : nums) { + cnt[num]++; + } + return cnt; + } + + private int[] buildGroupCounts(int[] cnt, int max) { + int[] groupCnt = new int[max + 1]; + + for (int i = 1; i <= max; i++) { + for (int j = 1; j * i <= max; j++) { + groupCnt[i] += cnt[j * i]; + } + } + + return groupCnt; + } + + private int findBestAboveMaxVal(int max, int maxVal, int[] cnt, int[] groupCnt) { + int best = -1; + + for (int i = max; i > maxVal; i--) { + if (cnt[i] == 0) { + continue; + } + + int change = countConflict(i, groupCnt); + best = Math.max(best, i - change + 1); + } + + return best; + } + + private int findBestWithinMaxVal(int maxVal, int[] cnt, int[] groupCnt, int best) { + + for (int i = maxVal; i > 0; i--) { + if (best != -1 && i <= best) { + break; + } + + int change = countConflict(i, groupCnt); + change = adjustChange(i, change, cnt); + + best = Math.max(best, i - change); + } + + return best; + } + + private int adjustChange(int target, int change, int[] cnt) { + if (change > 0 && cnt[target] != 0) { + change--; + } + + if (change == 0 && cnt[target] == 0) { + change++; + } + + return change; + } + + private int countConflict(int target, int[] groupCnt) { + List primeFactors = getFactor(target); + int change = 0; + int subsetCount = 1 << primeFactors.size(); + + for (int mask = 1; mask < subsetCount; mask++) { + change += calculateSubsetContribution(mask, primeFactors, groupCnt); + } + + return change; + } + + private int calculateSubsetContribution(int mask, List primeFactors, int[] groupCnt) { + + int product = 1; + int bits = 0; + + for (int k = 0; k < primeFactors.size(); k++) { + if ((mask & (1 << k)) == 0) { + continue; + } + + bits++; + product *= primeFactors.get(k); + } + + int contribution = groupCnt[product]; + return bits % 2 == 1 ? contribution : -contribution; + } + + private List getFactor(long number) { + long n = number; + List primeFactors = new ArrayList<>(); + + for (int i = 2; i <= n / i; i++) { + if (n % i != 0) { + continue; + } + + primeFactors.add(i); + while (n % i == 0) { + n /= i; + } + } + + if (n > 1) { + primeFactors.add((int) n); + } + + return primeFactors; + } +} diff --git a/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/readme.md b/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/readme.md new file mode 100644 index 000000000..5e17edae2 --- /dev/null +++ b/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/readme.md @@ -0,0 +1,68 @@ +3953\. Maximum Score with Co-Prime Element + +Hard + +You are given an integer array `nums` of length `n` and an integer `maxVal`. + +You **may** change any element in `nums` to any positive integer **less than or equal** to `maxVal`. Each such change costs 1. + +Two integers are **co-prime** if their **greatest common divisor (GCD)** is 1. + +After all modifications, you **must** choose an index `i` such that, `nums[i]` is **co-prime** with every other element `nums[j]`. + +Let: + +* `selectedValue` be the final value of `nums[i]` after modifications. +* `modificationCost` be the total number of elements changed. + +The score is defined as `score = selectedValue - modificationCost`. + +Return the **maximum** possible score. + +**Example 1:** + +**Input:** nums = [3,4,6], maxVal = 5 + +**Output:** 4 + +**Explanation:** + +Change `nums[2]` from 6 to 5, which costs 1. Choose `nums[2] = 5`, since it is co-prime with 3 and 4. + +* `selectedValue = 5` +* `modificationCost = 1` +* The score is `5 - 1 = 4` + +**Example 2:** + +**Input:** nums = [1,2,3], maxVal = 4 + +**Output:** 3 + +**Explanation:** + +No modifications are required. Choose `nums[2] = 3`, since it is co-prime with 1 and 2. + +* `selectedValue = 3` +* `modificationCost = 0` +* The score is `3 - 0 = 3` + +**Example 3:** + +**Input:** nums = [2,2], maxVal = 1 + +**Output:** 1 + +**Explanation:** + +Change `nums[0]` from 2 to 1, which costs 1. Choose `nums[1] = 2`, since it is co-prime with 1. + +* `selectedValue = 2` +* `modificationCost = 1` +* The score is `2 - 1 = 1` + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 +* 1 <= maxVal <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/Solution.java b/src/main/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/Solution.java new file mode 100644 index 000000000..986cc1b7f --- /dev/null +++ b/src/main/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/Solution.java @@ -0,0 +1,21 @@ +package g3901_4000.s3954_sum_of_compatible_numbers_in_range_i; + +// #Easy #Dynamic_Programming #Bit_Manipulation #Enumeration #Mid_Level #Weekly_Contest_505 +// #2026_10_20_Time_1_ms_(100.00%)_Space_42.37_MB_(88.29%) + +public class Solution { + public int sumOfGoodIntegers(int n, int k) { + int sum = 0; + int l = k + n; + int s = n - k; + if (s < 0) { + s = 1; + } + for (int i = s; i <= l; i++) { + if ((i & n) == 0) { + sum += i; + } + } + return sum; + } +} diff --git a/src/main/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/readme.md b/src/main/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/readme.md new file mode 100644 index 000000000..7fa5969f6 --- /dev/null +++ b/src/main/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/readme.md @@ -0,0 +1,48 @@ +3954\. Sum of Compatible Numbers in Range I + +Easy + +You are given two integers `n` and `k`. + +A **positive** integer `x` is called **compatible** if it satisfies both of the following conditions: + +* `abs(n - x) <= k` +* `(n & x) == 0` + +Return the sum of all **compatible** integers `x`. + +**Note**: + +* Here, `&` denotes the **bitwise AND** operator. +* The **absolute** difference between integers `i` and `j` is defined as `abs(i - j)`. + +**Example 1:** + +**Input:** n = 2, k = 3 + +**Output:** 10 + +**Explanation:** + +The compatible integers are: + +* `x = 1`, since `abs(2 - 1) = 1` and `2 & 1 = 0`. +* `x = 4`, since `abs(2 - 4) = 2` and `2 & 4 = 0`. +* `x = 5`, since `abs(2 - 5) = 3` and `2 & 5 = 0`. + +Thus, the answer is `1 + 4 + 5 = 10`. + +**Example 2:** + +**Input:** n = 5, k = 1 + +**Output:** 0 + +**Explanation:** + +There are no compatible integers in the range `[4, 6]`. Thus, the answer is 0. + +**Constraints:** + +* `1 <= n <= 100` +* `1 <= k <= 100` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/Solution.java b/src/main/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/Solution.java new file mode 100644 index 000000000..254add0d4 --- /dev/null +++ b/src/main/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/Solution.java @@ -0,0 +1,36 @@ +package g3901_4000.s3955_valid_binary_strings_with_cost_limit; + +// #Medium #String #Bit_Manipulation #Backtracking #Enumeration #Senior #Weekly_Contest_505 +// #2026_10_20_Time_5_ms_(96.05%)_Space_46.65_MB_(99.60%) + +import java.util.ArrayList; +import java.util.List; + +public class Solution { + private List result; + private int n; + private int k; + + public List generateValidStrings(int n, int k) { + this.result = new ArrayList<>(); + this.n = n; + this.k = k; + char[] path = new char[n]; + dfs(0, 0, path); + return result; + } + + private void dfs(int index, int cost, char[] path) { + if (index == n) { + result.add(new String(path)); + return; + } + path[index] = '0'; + dfs(index + 1, cost, path); + boolean canPlaceOne = (index == 0 || path[index - 1] != '1') && (cost + index <= k); + if (canPlaceOne) { + path[index] = '1'; + dfs(index + 1, cost + index, path); + } + } +} diff --git a/src/main/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/readme.md b/src/main/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/readme.md new file mode 100644 index 000000000..ca56a8bc4 --- /dev/null +++ b/src/main/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/readme.md @@ -0,0 +1,51 @@ +3955\. Valid Binary Strings With Cost Limit + +Medium + +You are given two integers `n` and `k`. + +The **cost** of a binary string `s` is defined as the sum of all indices `i` (0-based) such that `s[i] == '1'`. + +A binary string is considered **valid** if: + +* It does not contain two consecutive `'1'` characters. +* Its cost is **less than or equal** to `k`. + +Return a list of all valid binary strings of length `n` in any order. + +**Example 1:** + +**Input:** n = 3, k = 1 + +**Output:** ["000","010","100"] + +**Explanation:** + +The binary strings of length 3 without consecutive `'1'` characters are: + +* `"000"` : `cost = 0` +* "`100"` : `cost = 0` +* `"010"` : `cost = 1` +* `"001"` : `cost = 2` +* `"101"` : `cost = 0 + 2 = 2` + +Among these, the strings with cost less than or equal to `k = 1` are `"000"`, `"010"` and `"100"`. + +Thus, the valid strings are `["000", "010", "100"]`. + +**Example 2:** + +**Input:** n = 1, k = 0 + +**Output:** ["0","1"] + +**Explanation:** + +The valid binary strings of length 1 are `"0"` and `"1"`. + +Thus the answer is `["0", "1"]`. + +**Constraints:** + +* `1 <= n <= 12` +* `0 <= k <= n * (n - 1) / 2` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/Solution.java b/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/Solution.java new file mode 100644 index 000000000..165738307 --- /dev/null +++ b/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/Solution.java @@ -0,0 +1,62 @@ +package g3901_4000.s3956_maximum_sum_of_m_non_overlapping_subarrays_i; + +// #Hard #Array #Dynamic_Programming #Binary_Search #Prefix_Sum #Sliding_Window #Queue +// #Monotonic_Queue #Senior_Staff #Weekly_Contest_505 +// #2026_10_20_Time_61_ms_(91.07%)_Space_46.56_MB_(83.93%) + +public class Solution { + public long maximumSum(int[] nums, int m, int l, int r) { + int n = nums.length; + long[] pre = new long[n + 1]; + for (int i = 0; i < n; i++) { + pre[i + 1] = pre[i] + nums[i]; + } + long neg = -(long) 4e18; + long[] prev = new long[n + 1]; + for (int i = 0; i <= n; i++) { + prev[i] = 0; + } + long res = neg; + for (int t = 1; t <= m; t++) { + long[] curr = new long[n + 1]; + for (int i = 0; i <= n; i++) { + curr[i] = neg; + } + int[] dq = new int[n + 1]; + int head = 0; + int tail = 0; + for (int i = 1; i <= n; i++) { + curr[i] = curr[i - 1]; + int add = i - l; + if (add >= 0 && prev[add] != neg) { + long val = prev[add] - pre[add]; + while (head < tail) { + int idx = dq[tail - 1]; + long last = prev[idx] - pre[idx]; + if (last <= val) { + tail--; + } else { + break; + } + } + dq[tail++] = add; + } + + int left = i - r; + while (head < tail && dq[head] < left) { + head++; + } + + if (head < tail) { + int s = dq[head]; + curr[i] = Math.max(curr[i], pre[i] + prev[s] - pre[s]); + } + } + + res = Math.max(res, curr[n]); + prev = curr; + } + + return res; + } +} diff --git a/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/readme.md b/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/readme.md new file mode 100644 index 000000000..a25e1b604 --- /dev/null +++ b/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/readme.md @@ -0,0 +1,67 @@ +3956\. Maximum Sum of M Non-Overlapping Subarrays I + +Hard + +You are given an integer array `nums` of length `n`, and three integers `m`, `l`, and `r`. + +Your task is to select **at least** one and **at most** `m` **non-overlapping non-empty subarrays** from `nums` such that: + +* Each selected **subarray** has a length between `[l, r]` (inclusive). +* The total sum of all selected **subarrays** is **maximized**. + +Return the **maximum** total sum you can achieve. + +**Example 1:** + +**Input:** nums = [4,1,-5,2], m = 2, l = 1, r = 3 + +**Output:** 7 + +**Explanation:** + +One optimal strategy is to: + +* Select the subarray `[4, 1]` with sum `4 + 1 = 5` and the subarray `[2]` with sum 2. Both subarrays have length between `[l, r]`. +* The total sum of these subarrays is `5 + 2 = 7`, which is the maximum achievable sum with at most `m = 2` subarrays. + +**Example 2:** + +**Input:** nums = [1,0,3,4], m = 2, l = 1, r = 2 + +**Output:** 8 + +**Explanation:** + +One optimal strategy is to: + +* Select the subarray `[1]` with sum `1` and the subarray `[3, 4]` with sum `3 + 4 = 7`. Both subarrays have length between `[l, r]`. +* The total sum of these subarrays is `1 + 7 = 8`, which is the maximum achievable sum with at most `m = 2` subarrays. + +**Example 3:** + +**Input:** nums = [-1,7,-4], m = 1, l = 2, r = 3 + +**Output:** 6 + +**Explanation:** + +* Select the subarray `[-1, 7]` from `nums` which has length between `[l, r]`. +* The total sum of this subarray is `-1 + 7 = 6`, which is the maximum achievable sum with at most `m = 1` subarray. + +**Example 4:** + +**Input:** nums = [-3,-4,-1], m = 2, l = 1, r = 2 + +**Output:** \-1 + +**Explanation:** + +* All subarrays of `nums` have negative sums. The optimal strategy is to select the subarray `[-1]`, which has length between `[l, r]`. +* The total sum of this subarray is -1, which is the maximum achievable sum with at most `m = 2` subarrays. + +**Constraints:** + +* `1 <= n == nums.length <= 1000` +* -109 <= nums[i] <= 109 +* `1 <= m <= n` +* `1 <= l <= r <= n` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java b/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java new file mode 100644 index 000000000..ca4767ae3 --- /dev/null +++ b/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java @@ -0,0 +1,119 @@ +package g3901_4000.s3957_maximum_sum_of_m_non_overlapping_subarrays_ii; + +// #Hard #Array #Dynamic_Programming #Binary_Search #Prefix_Sum #Sliding_Window #Queue +// #Monotonic_Queue #Weekly_Contest_505 #Principal +// #2026_10_20_Time_98_ms_(93.55%)_Space_104.56_MB_(90.32%) + +public class Solution { + private long[] pre; + private long[] val; + private int[] cnt; + private int[] dq; + private int n; + private int l; + private int r; + + public long maximumSum(int[] nums, int m, int l, int r) { + n = nums.length; + this.l = l; + this.r = r; + pre = new long[n + 1]; + for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + nums[i]; + val = new long[n + 1]; + cnt = new int[n + 1]; + dq = new int[n + 2]; + + long lo = 0; + long hi = 20000000000L; + long ansLambda = hi; + solve(0); + if (cnt[n] <= m) return val[n]; + while (lo <= hi) { + long mid = lo + (hi - lo) / 2; + solve(mid); + if (cnt[n] <= m) { + ansLambda = mid; + hi = mid - 1; + } else lo = mid + 1; + } + solve(ansLambda); + return val[n] + ansLambda * m; + } + + private void solve(long lambda) { + final long neg = Long.MIN_VALUE / 4; + val[0] = neg; + cnt[0] = 0; + + int head = 0; + int tail = 0; + + for (int i = 1; i <= n; i++) { + int j = i - l; + + if (j >= 0) { + tail = addCandidate(j, head, tail); + } + + head = removeExpiredCandidates(head, tail, i - r); + + long bestV = val[i - 1]; + int bestC = cnt[i - 1]; + + if (tail > head) { + int b = dq[head]; + long cand = normalizedValue(b) - pre[b] + pre[i] - lambda; + int candC = normalizedCount(b) + 1; + + if (isBetter(cand, candC, bestV, bestC)) { + bestV = cand; + bestC = candC; + } + } + + val[i] = bestV; + cnt[i] = bestC; + } + } + + private int addCandidate(int j, int head, int tail) { + long key = normalizedValue(j) - pre[j]; + int candidateCount = normalizedCount(j); + + while (tail > head) { + int t = dq[tail - 1]; + long tailKey = normalizedValue(t) - pre[t]; + int tailCount = normalizedCount(t); + + if (tailKey < key || (tailKey == key && tailCount >= candidateCount)) { + tail--; + } else { + break; + } + } + + dq[tail++] = j; + return tail; + } + + private int removeExpiredCandidates(int head, int tail, int minIndex) { + while (tail > head && dq[head] < minIndex) { + head++; + } + return head; + } + + private long normalizedValue(int index) { + return val[index] > 0 ? val[index] : 0; + } + + private int normalizedCount(int index) { + return val[index] > 0 ? cnt[index] : 0; + } + + private boolean isBetter( + long candidateValue, int candidateCount, long bestValue, int bestCount) { + return candidateValue > bestValue + || (candidateValue == bestValue && candidateCount < bestCount); + } +} diff --git a/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/readme.md b/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/readme.md new file mode 100644 index 000000000..a6e9a7a5b --- /dev/null +++ b/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/readme.md @@ -0,0 +1,67 @@ +3957\. Maximum Sum of M Non-Overlapping Subarrays II + +Hard + +You are given an integer array `nums` of length `n`, and three integers `m`, `l`, and `r`. + +Your task is to select **at least** one and **at most** `m` **non-overlapping non-empty subarrays** from `nums` such that: + +* Each selected **subarray** has a length between `[l, r]` (inclusive). +* The total sum of all selected **subarrays** is **maximized**. + +Return the **maximum** total sum you can achieve. + +**Example 1:** + +**Input:** nums = [4,1,-5,2], m = 2, l = 1, r = 3 + +**Output:** 7 + +**Explanation:** + +One optimal strategy is to: + +* Select the subarray `[4, 1]` with sum `4 + 1 = 5` and the subarray `[2]` with sum 2. Both subarrays have length between `[l, r]`. +* The total sum of these subarrays is `5 + 2 = 7`, which is the maximum achievable sum with at most `m = 2` subarrays. + +**Example 2:** + +**Input:** nums = [1,0,3,4], m = 2, l = 1, r = 2 + +**Output:** 8 + +**Explanation:** + +One optimal strategy is to: + +* Select the subarray `[1]` with sum `1` and the subarray `[3, 4]` with sum `3 + 4 = 7`. Both subarrays have length between `[l, r]`. +* The total sum of these subarrays is `1 + 7 = 8`, which is the maximum achievable sum with at most `m = 2` subarrays. + +**Example 3:** + +**Input:** nums = [-1,7,-4], m = 1, l = 2, r = 3 + +**Output:** 6 + +**Explanation:** + +* Select the subarray `[-1, 7]` from `nums` which has length between `[l, r]`. +* The total sum of this subarray is `-1 + 7 = 6`, which is the maximum achievable sum with at most `m = 1` subarray. + +**Example 4:** + +**Input:** nums = [-3,-4,-1], m = 2, l = 1, r = 2 + +**Output:** \-1 + +**Explanation:** + +* All subarrays of `nums` have negative sums. The optimal strategy is to select the subarray `[-1]`, which has length between `[l, r]`. +* The total sum of this subarray is -1, which is the maximum achievable sum with at most `m = 2` subarrays. + +**Constraints:** + +* 1 <= n == nums.length <= 105 +* -105 <= nums[i] <= 105 +* `1 <= m <= n` +* `1 <= l <= r <= n` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3959_check_good_integer/Solution.java b/src/main/java/g3901_4000/s3959_check_good_integer/Solution.java new file mode 100644 index 000000000..d97cd7189 --- /dev/null +++ b/src/main/java/g3901_4000/s3959_check_good_integer/Solution.java @@ -0,0 +1,16 @@ +package g3901_4000.s3959_check_good_integer; + +// #Easy #Math #Simulation #Mid_Level #Weekly_Contest_506 +// #2026_10_20_Time_1_ms_(92.77%)_Space_42.13_MB_(93.32%) + +public class Solution { + public boolean checkGoodInteger(int n) { + int sum = 0; + while (n > 0) { + int digit = n % 10; + sum += digit * digit - digit; + n /= 10; + } + return sum >= 50; + } +} diff --git a/src/main/java/g3901_4000/s3959_check_good_integer/readme.md b/src/main/java/g3901_4000/s3959_check_good_integer/readme.md new file mode 100644 index 000000000..def91262d --- /dev/null +++ b/src/main/java/g3901_4000/s3959_check_good_integer/readme.md @@ -0,0 +1,41 @@ +3959\. Check Good Integer + +Easy + +You are given a positive integer `n`. + +Let `digitSum` be the sum of the digits of `n`, and let `squareSum` be the sum of the squares of the digits of `n`. + +An integer is called **good** if `squareSum - digitSum >= 50`. + +Return `true` if `n` is good. Otherwise, return `false`. + +**Example 1:** + +**Input:** n = 1000 + +**Output:** false + +**Explanation:** + +* The digits of 1000 are 1, 0, 0, and 0. +* The `digitSum` is `1 + 0 + 0 + 0 = 1`. +* The `squareSum` is 12 + 02 + 02 + 02 = 1. +* The `squareSum - digitSum` is `1 - 1 = 0`. As 0 is not greater than or equal to 50, the output is `false`. + +**Example 2:** + +**Input:** n = 19 + +**Output:** true + +**Explanation:** + +* The digits of 19 are 1 and 9. +* The `digitSum` is `1 + 9 = 10`. +* The `squareSum` is 12 + 92 = 1 + 81 = 82. +* The `squareSum - digitSum` is `82 - 10 = 72`. As 72 is greater than or equal to 50, the output is `true`. + +**Constraints:** + +* 1 <= n <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3960_frequency_balance_subarray/Solution.java b/src/main/java/g3901_4000/s3960_frequency_balance_subarray/Solution.java new file mode 100644 index 000000000..77e7fe4aa --- /dev/null +++ b/src/main/java/g3901_4000/s3960_frequency_balance_subarray/Solution.java @@ -0,0 +1,39 @@ +package g3901_4000.s3960_frequency_balance_subarray; + +// #Medium #Array #Hash_Table #Counting #Senior #Weekly_Contest_506 +// #2026_10_20_Time_264_ms_(98.53%)_Space_46.59_MB_(97.06%) + +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int getLength(int[] a) { + int n = a.length; + int ans = 1; + for (int i = 0; i < n; i++) { + Map mp = new HashMap<>(); + int[] fq = new int[n + 1]; + int mx = 0; + int s = 0; + for (int j = i; j < n; j++) { + int old = mp.getOrDefault(a[j], 0); + if (old > 0) { + fq[old]--; + } + mp.put(a[j], old + 1); + fq[old + 1]++; + if (old + 1 > mx) { + mx = old + 1; + s = 1; + } else if (old + 1 == mx) { + s++; + } + int distinct = mp.size(); + if (distinct == 1 || (mx % 2 == 0 && s < distinct && fq[mx / 2] == distinct - s)) { + ans = Math.max(ans, j - i + 1); + } + } + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3960_frequency_balance_subarray/readme.md b/src/main/java/g3901_4000/s3960_frequency_balance_subarray/readme.md new file mode 100644 index 000000000..f89925f5c --- /dev/null +++ b/src/main/java/g3901_4000/s3960_frequency_balance_subarray/readme.md @@ -0,0 +1,51 @@ +3960\. Frequency Balance Subarray + +Medium + +You are given an integer array `nums`. + +Define a **frequency balance non-empty subarrays** as follows: + +* If the subarray contains only one distinct value, it is frequency balanced. +* Otherwise, there must exist a positive integer `f` such that every distinct value in the subarray occurs either `f` or `2 * f` times, and both frequencies occur among the distinct values. + +Return an integer denoting the length of the **longest** frequency balance subarray. + +**Example 1:** + +**Input:** nums = [1,2,2,1,2,3,3,3] + +**Output:** 5 + +**Explanation:** + +* The longest frequency balance subarray is `[2, 1, 2, 3, 3]`. +* The elements that appear most frequently are 2 and 3, both appearing twice. +* The remaining element 1 appears once, meeting the requirements. + +**Example 2:** + +**Input:** nums = [5,5,5,5] + +**Output:** 4 + +**Explanation:** + +* The longest frequency balance subarray is `[5, 5, 5, 5]`. +* The element that appears most frequently is 5. +* There are no other elements meeting the requirements. + +**Example 3:** + +**Input:** nums = [1,2,3,4] + +**Output:** 1 + +**Explanation:** + +Since all elements appear only once, the length of the longest frequency balance subarray is 1. + +**Constraints:** + +* 1 <= nums.length <= 103 +* 1 <= nums[i] <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3961_maximize_sum_of_device_ratings/Solution.java b/src/main/java/g3901_4000/s3961_maximize_sum_of_device_ratings/Solution.java new file mode 100644 index 000000000..a89ec2c36 --- /dev/null +++ b/src/main/java/g3901_4000/s3961_maximize_sum_of_device_ratings/Solution.java @@ -0,0 +1,41 @@ +package g3901_4000.s3961_maximize_sum_of_device_ratings; + +// #Medium #Array #Sorting #Greedy #Matrix #Staff #Weekly_Contest_506 +// #2026_10_20_Time_6_ms_(98.67%)_Space_209.82_MB_(68.00%) + +public class Solution { + public long maxRatings(int[][] nums) { + int n = nums[0].length; + if (n == 1) { + long totalSum = 0; + for (int[] num : nums) { + totalSum += num[0]; + } + return totalSum; + } + long sumM2 = 0; + int min1Global = Integer.MAX_VALUE; + int min2Global = Integer.MAX_VALUE; + for (int[] num : nums) { + int min1 = Integer.MAX_VALUE; + int min2 = Integer.MAX_VALUE; + for (int j = 0; j < n; j++) { + int val = num[j]; + if (val < min1) { + min2 = min1; + min1 = val; + } else if (val < min2) { + min2 = val; + } + } + sumM2 += min2; + if (min1 < min1Global) { + min1Global = min1; + } + if (min2 < min2Global) { + min2Global = min2; + } + } + return min1Global + sumM2 - min2Global; + } +} diff --git a/src/main/java/g3901_4000/s3961_maximize_sum_of_device_ratings/readme.md b/src/main/java/g3901_4000/s3961_maximize_sum_of_device_ratings/readme.md new file mode 100644 index 000000000..f52680d31 --- /dev/null +++ b/src/main/java/g3901_4000/s3961_maximize_sum_of_device_ratings/readme.md @@ -0,0 +1,65 @@ +3961\. Maximize Sum of Device Ratings + +Medium + +You are given a 2D integer array `units` of size `m × n` where `units[i][j]` represents the capacity of the jth unit in the ith device. Each device contains **exactly** `n` units. + +The **rating** of a device is the **minimum** capacity among all its units. + +You may perform the following operation any number of times (including zero): + +* Choose a device `i` that has **not been** used as a source before. +* Remove **exactly** one unit from device `i` and add it to **any** different device. +* Then mark device `i` as used, so it cannot be chosen again as a source. + +Return the **maximum** possible sum of the ratings of all devices after any number of such operations. + +**Note:** + +* Devices can receive units from multiple devices, regardless of whether they have been selected. +* The rating of an empty device is 0. + +**Example 1:** + +**Input:** units = [[1,3],[2,2]] + +**Output:** 4 + +**Explanation:** + +* Select device `i = 0` and transfer `units[0][0] = 1` to device `i = 1`. +* After the transfer, the ratings are: + * Device `0 = [3]`: `rating[0] = 3` + * Device 1 = [2, 2, 1]: `rating[1] = 1` +* Thus, the sum of ratings is `3 + 1 = 4`. + +**Example 2:** + +**Input:** units = [[1,2,3],[4,5,6]] + +**Output:** 6 + +**Explanation:** + +* Select device `i = 1` and transfer `units[1][0] = 4` to device `i = 0`. +* After the transfer, the ratings are: + * Device 0 = [1, 2, 3, 4]: `rating[0] = 1` + * Device `1 = [5, 6]`: `rating[1] = 5` +* Thus, the sum of ratings is `1 + 5 = 6`. + +**Example 3:** + +**Input:** units = [[5,5,5],[1,1,1]] + +**Output:** 6 + +**Explanation:** + +* No transfers increase the sum of ratings. Thus, the sum of ratings is `5 + 1 = 6`. + +**Constraints:** + +* 1 <= m == units.length <= 105 +* 1 <= n == units[i].length <= 105 +* m * n <= 2 * 105 +* 1 <= units[i][j] <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java new file mode 100644 index 000000000..0256db333 --- /dev/null +++ b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java @@ -0,0 +1,211 @@ +package g3901_4000.s3962_maximum_subarray_sum_after_at_most_k_swaps; + +// #Hard #Array #Hash_Table #Sorting #Greedy #Heap_Priority_Queue #Ordered_Set #Binary_Indexed_Tree +// #Senior_Staff #Weekly_Contest_506 #2026_10_20_Time_13_ms_(98.61%)_Space_45.05_MB_(100.00%) + +import java.util.Arrays; + +public class Solution { + public long maxSum(int[] nums, int k) { + if (k == 0) { + return maxSubarraySum(nums); + } + PositiveInfo info = analyzePositiveValues(nums); + if (info.count == 0) { + return info.maxElement; + } + int maxPositiveWindow = findMaxPositiveWindow(nums, info.count); + if (k >= info.count - maxPositiveWindow) { + return info.sum; + } + int[] values = getUniqueSortedValues(nums); + int[] map = mapValues(nums, values); + int[] totalCounts = countMappedValues(map, values.length); + return findBestSum(nums, k, values, map, totalCounts); + } + + private long maxSubarraySum(int[] nums) { + long max = nums[0]; + long cur = nums[0]; + for (int i = 1; i < nums.length; i++) { + cur = Math.max(nums[i], cur + nums[i]); + max = Math.max(max, cur); + } + return max; + } + + private PositiveInfo analyzePositiveValues(int[] nums) { + int count = 0; + long sum = 0; + long maxElement = Long.MIN_VALUE; + for (int x : nums) { + if (x > 0) { + sum += x; + count++; + } + maxElement = Math.max(maxElement, x); + } + return new PositiveInfo(count, sum, maxElement); + } + + private int findMaxPositiveWindow(int[] nums, int windowSize) { + int current = 0; + int max = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] > 0) { + current++; + } + if (i >= windowSize && nums[i - windowSize] > 0) { + current--; + } + if (i >= windowSize - 1) { + max = Math.max(max, current); + } + } + return max; + } + + private int[] getUniqueSortedValues(int[] nums) { + int[] sorted = nums.clone(); + Arrays.sort(sorted); + int size = 0; + for (int x : sorted) { + if (size == 0 || sorted[size - 1] != x) { + sorted[size++] = x; + } + } + return Arrays.copyOf(sorted, size); + } + + private int[] mapValues(int[] nums, int[] values) { + int[] map = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { + map[i] = Arrays.binarySearch(values, nums[i]); + } + return map; + } + + private int[] countMappedValues(int[] map, int size) { + int[] counts = new int[size]; + for (int index : map) { + counts[index]++; + } + return counts; + } + + private long findBestSum(int[] nums, int k, int[] values, int[] map, int[] totalCounts) { + long best = Long.MIN_VALUE; + int[] included = new int[values.length]; + for (int i = 0; i < nums.length; i++) { + Arrays.fill(included, 0); + SwapContext context = new SwapContext(values, included, totalCounts); + best = evaluateStartingPosition(nums, i, k, map, context, best); + } + return best; + } + + private long evaluateStartingPosition( + int[] nums, int start, int k, int[] map, SwapContext context, long best) { + long sum = 0; + int minIndex = context.values.length; + int maxOutside = context.values.length - 1; + for (int j = start; j < nums.length; j++) { + int index = map[j]; + context.included[index]++; + sum += nums[j]; + minIndex = Math.min(minIndex, index); + maxOutside = findMaxOutside(maxOutside, context); + if (hasNoUsefulSwap(minIndex, maxOutside, context.values)) { + best = Math.max(best, sum); + } else if (sum + (long) k * (context.values[maxOutside] - context.values[minIndex]) + > best) { + long candidate = optimizeSwaps(k, sum, minIndex, maxOutside, context); + best = Math.max(best, candidate); + } + } + return best; + } + + private int findMaxOutside(int maxOutside, SwapContext context) { + while (maxOutside >= 0 && context.totalCounts[maxOutside] == context.included[maxOutside]) { + maxOutside--; + } + return maxOutside; + } + + private boolean hasNoUsefulSwap(int minIndex, int maxOutside, int[] values) { + return maxOutside < 0 || values[minIndex] >= values[maxOutside]; + } + + private long optimizeSwaps(int k, long sum, int minIndex, int maxOutside, SwapContext context) { + int[] values = context.values; + int[] included = context.included; + int[] totalCounts = context.totalCounts; + long result = sum; + int swaps = 0; + int left = minIndex; + int right = maxOutside; + int leftCount = included[left]; + int rightCount = totalCounts[right] - included[right]; + + while (swaps < k && left < right) { + if (leftCount == 0) { + left++; + if (left < right) { + leftCount = included[left]; + } + } else if (rightCount == 0) { + right--; + if (left < right) { + rightCount = totalCounts[right] - included[right]; + } + } else if (values[left] >= values[right]) { + break; + } else { + int take = Math.min(k - swaps, Math.min(leftCount, rightCount)); + result += (long) take * (values[right] - values[left]); + swaps += take; + leftCount -= take; + rightCount -= take; + } + } + return result; + } + + private record SwapContext(int[] values, int[] included, int[] totalCounts) { + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof SwapContext(int[] values1, int[] included1, int[] counts))) { + return false; + } + return Arrays.equals(values, values1) + && Arrays.equals(included, included1) + && Arrays.equals(totalCounts, counts); + } + + @Override + public int hashCode() { + int result = Arrays.hashCode(values); + result = 31 * result + Arrays.hashCode(included); + result = 31 * result + Arrays.hashCode(totalCounts); + return result; + } + + @Override + public String toString() { + return "SwapContext[values=" + + Arrays.toString(values) + + ", included=" + + Arrays.toString(included) + + ", totalCounts=" + + Arrays.toString(totalCounts) + + "]"; + } + } + + private record PositiveInfo(int count, long sum, long maxElement) {} +} diff --git a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/readme.md b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/readme.md new file mode 100644 index 000000000..242118467 --- /dev/null +++ b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/readme.md @@ -0,0 +1,50 @@ +3962\. Maximum Subarray Sum After at Most K Swaps + +Hard + +You are given an integer array `nums` and an integer `k`. + +You are allowed to perform **at most** `k` swap operations on the array. + +In one swap operation, you may choose any two indices `i` and `j` and swap `nums[i]` and `nums[j]`. + +Return an integer denoting the **maximum possible non-empty subarrays sum** after performing the swaps. + +**Example 1:** + +**Input:** nums = [1,-1,0,2], k = 1 + +**Output:** 3 + +**Explanation:** + +* We can swap on indices 1 and 3, resulting in the array `[1, 2, 0, -1]`. +* The subarray `[1, 2]` has a sum of 3, which is the maximum possible subarray sum after at most `k = 1` swap. + +**Example 2:** + +**Input:** nums = [4,3,2,4], k = 2 + +**Output:** 13 + +**Explanation:** + +The maximum possible subarray sum after at most `k = 2` swaps is the sum of the entire array, which is 13. + +**Example 3:** + +**Input:** nums = [-1,-2], k = 0 + +**Output:** \-1 + +**Explanation:** + +* `k = 0` swaps are allowed. +* The possible subarrays are `[-1]`, `[-2]`, and `[-1, -2]`, with sums -1, -2, and -3 respectively. +* Among these sums, the maximum is -1. + +**Constraints:** + +* `1 <= nums.length <= 1500` +* -105 <= nums[i] <= 105 +* `0 <= k <= nums.length` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3963_create_grid_with_exactly_one_path/Solution.java b/src/main/java/g3901_4000/s3963_create_grid_with_exactly_one_path/Solution.java new file mode 100644 index 000000000..66e2bc0a0 --- /dev/null +++ b/src/main/java/g3901_4000/s3963_create_grid_with_exactly_one_path/Solution.java @@ -0,0 +1,19 @@ +package g3901_4000.s3963_create_grid_with_exactly_one_path; + +// #Easy #Mid_Level #Biweekly_Contest_185 #2026_10_20_Time_2_ms_(92.91%)_Space_45.85_MB_(97.87%) + +public class Solution { + public String[] createGrid(int m, int n) { + var res = new String[m]; + var sb = new StringBuilder(); + sb.repeat(".", Math.max(0, n)); + res[0] = sb.toString(); + sb = new StringBuilder(); + sb.repeat("#", Math.max(0, n - 1)); + sb.append("."); + for (var i = 1; i < m; i++) { + res[i] = sb.toString(); + } + return res; + } +} diff --git a/src/main/java/g3901_4000/s3963_create_grid_with_exactly_one_path/readme.md b/src/main/java/g3901_4000/s3963_create_grid_with_exactly_one_path/readme.md new file mode 100644 index 000000000..1aad35b15 --- /dev/null +++ b/src/main/java/g3901_4000/s3963_create_grid_with_exactly_one_path/readme.md @@ -0,0 +1,58 @@ +3963\. Create Grid With Exactly One Path + +Easy + +You are given two integers `m` and `n`, representing the number of rows and columns of a grid. + +Construct **any** `m x n` grid consisting only of the characters `'.'` and `'#'`, where: + +* `'.'` represents a free cell. +* `'#'` represents an obstacle cell. + +A **valid path** is a sequence of free cells that: + +* Starts at the top-left cell `(0, 0)`. +* Ends at the bottom-right cell `(m - 1, n - 1)`. +* Moves only: + * Right, from `(i, j)` to `(i, j + 1)`, or + * Down, from `(i, j)` to `(i + 1, j)`. + +Return any grid such that there is **exactly one valid path** from the top-left cell to the bottom-right cell. + +**Example 1:** + +**Input:** m = 2, n = 3 + +**Output:** ["..#","#.."] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2026/05/26/screenshot-2026-05-26-at-61005pm.png) + +The only valid path is: `(0,0) → (0,1) → (1,1) → (1,2)` + +**Example 2:** + +**Input:** m = 3, n = 3 + +**Output:** ["..#","#..","##."] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2026/05/26/screenshot-2026-05-26-at-61129pm.png) + +The only valid path is: `(0,0) → (0,1) → (1,1) → (1,2) → (2,2)` + +**Example 3:** + +**Input:** m = 1, n = 4 + +**Output:** ["...."] + +**Explanation:** + +The only valid path is: `(0,0) → (0,1) → (0,2) → (0,3)` + +**Constraints:** + +* `1 <= m, n <= 25` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/Solution.java b/src/main/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/Solution.java new file mode 100644 index 000000000..09457d95c --- /dev/null +++ b/src/main/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/Solution.java @@ -0,0 +1,29 @@ +package g3901_4000.s3964_minimum_lights_to_illuminate_a_road; + +// #Medium #Array #Prefix_Sum #Staff #Biweekly_Contest_185 +// #2026_10_20_Time_7_ms_(100.00%)_Space_204.80_MB_(14.68%) + +public class Solution { + public int minLights(int[] lights) { + int n = lights.length; + for (int i = 0; i < n; i++) { + if (lights[i] != 0) { + int pos = Math.max(0, i - lights[i]); + lights[pos] = Math.max(lights[i], lights[pos]); + } + } + int ans = 0; + int coverage = 0; + for (int i = 0; i < n; i++) { + if (lights[i] == 0 && coverage == 0) { + ans++; + if (i + 1 < n && lights[i + 1] == 0) { + coverage = 3; + } + } + coverage--; + coverage = Math.max(coverage, lights[i]); + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/readme.md b/src/main/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/readme.md new file mode 100644 index 000000000..2cf387cdc --- /dev/null +++ b/src/main/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/readme.md @@ -0,0 +1,48 @@ +3964\. Minimum Lights to Illuminate a Road + +Medium + +You are given an integer array `lights` of length `n`, representing positions 0 through `n - 1` on a road. + +For each position `i`: + +* If `lights[i] = v`, where `v > 0`, there is a working bulb at position `i` that **illuminates** every position from `max(0, i - v)` to `min(n - 1, i + v)`, inclusive. +* If `lights[i] = 0`, there is no working bulb at position `i`. + +A position is **visible** if it is illuminated by **at least** one working bulb. + +You may install **additional** bulbs at **any** positions. Each additional bulb installed at position `j` **illuminates** positions from `max(0, j - 1)` to `min(n - 1, j + 1)`, inclusive. + +Return the minimum number of additional bulbs required to make **every** position on the road visible. + +**Example 1:** + +**Input:** lights = [0,0,0,0] + +**Output:** 2 + +**Explanation:** + +One optimal placement is: + +* Install an additional bulb at position 1, illuminating positions `[0, 1, 2]`. +* Install an additional bulb at position 3, illuminating positions `[2, 3]`. + +Therefore, the minimum number of additional bulbs required is 2. + +**Example 2:** + +**Input:** lights = [0,0,0,2,0] + +**Output:** 1 + +**Explanation:** + +* Since `lights[3] = 2`, the working bulb at position 3 illuminates positions `[1, 2, 3, 4]`. +* Installing an additional bulb at position 1 illuminates positions `[0, 1, 2]`, making every position visible. +* Therefore, the minimum number of additional bulbs required is 1. + +**Constraints:** + +* 1 <= n == lights.length <= 105 +* `0 <= lights[i] <= n` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java b/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java new file mode 100644 index 000000000..5ea9ced27 --- /dev/null +++ b/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java @@ -0,0 +1,47 @@ +package g3901_4000.s3966_count_good_integers_in_a_range; + +// #Hard #Dynamic_Programming #Math #Senior_Staff #Biweekly_Contest_185 +// #2026_10_20_Time_3_ms_(100.00%)_Space_42.43_MB_(100.00%) + +public class Solution { + private static final Long[][][][] DP = new Long[16][2][10][10]; + private final int[] digits = new int[16]; + + public long goodIntegers(long l, long r, int k) { + return calc(r, k) - calc(l - 1, k); + } + + private long calc(long num, int k) { + int len = 0; + while (num > 0) { + digits[len++] = (int) (num % 10); + num /= 10; + } + return dfs(len - 1, 0, 1, true, k); + } + + private long dfs(int index, int pre, int isLeadingZero, boolean isMaxDigit, int k) { + if (index == -1) { + return 1; + } + if (!isMaxDigit && DP[index][isLeadingZero][pre][k] != null) { + return DP[index][isLeadingZero][pre][k]; + } + int maxDigit = isMaxDigit ? digits[index] : 9; + long result = 0; + for (int d = 0; d <= maxDigit; d++) { + if (isLeadingZero == 1 || Math.abs(d - pre) <= k) + result += + dfs( + index - 1, + d, + isLeadingZero == 1 && d == 0 ? 1 : 0, + isMaxDigit && d == maxDigit, + k); + } + if (!isMaxDigit) { + DP[index][isLeadingZero][pre][k] = result; + } + return result; + } +} diff --git a/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/readme.md b/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/readme.md new file mode 100644 index 000000000..ed73a19dc --- /dev/null +++ b/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/readme.md @@ -0,0 +1,43 @@ +3966\. Count Good Integers in a Range + +Hard + +You are given three integers `l`, `r` and `k`. + +A number is considered **good** if the **absolute difference** between every pair of **adjacent** digits is **at most** `k`. + +Return the number of **good** integers in the range `[l, r]` (inclusive). + +The **absolute difference** between values `x` and `y` is defined as `abs(x - y)`. + +**Example 1:** + +**Input:** l = 10, r = 15, k = 1 + +**Output:** 3 + +**Explanation:** + +* The good integers in the range are 10, 11, and 12. +* For 10, `abs(1 - 0) = 1`. +* For 11, `abs(1 - 1) = 0`. +* For 12, `abs(1 - 2) = 1`. +* All these differences are at most `k = 1`. Thus, the answer is 3. + +**Example 2:** + +**Input:** l = 201, r = 204, k = 2 + +**Output:** 2 + +**Explanation:** + +* The good integers in the range are 201 and 202. +* For 201, `abs(2 - 0) = 2` and `abs(0 - 1) = 1`. +* For 202, `abs(2 - 0) = 2` and `abs(0 - 2) = 2`. +* Thus, the answer is 2. + +**Constraints:** + +* 10 <= l <= r <= 1015 +* `0 <= k <= 9` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/Solution.java b/src/main/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/Solution.java new file mode 100644 index 000000000..0adde50fb --- /dev/null +++ b/src/main/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/Solution.java @@ -0,0 +1,14 @@ +package g3901_4000.s3968_maximum_manhattan_distance_after_all_moves; + +// #Medium #String #Math #Counting #Senior #Weekly_Contest_507 +// #2026_10_20_Time_7_ms_(99.64%)_Space_47.68_MB_(80.65%) + +public class Solution { + public int maxDistance(String s) { + int[] d = new int[96]; + for (char c : s.toCharArray()) { + d[c]++; + } + return Math.abs(d['U'] - d['D']) + Math.abs(d['L'] - d['R']) + d['_']; + } +} diff --git a/src/main/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/readme.md b/src/main/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/readme.md new file mode 100644 index 000000000..92d9bd9d2 --- /dev/null +++ b/src/main/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/readme.md @@ -0,0 +1,53 @@ +3968\. Maximum Manhattan Distance After All Moves + +Medium + +You are given a string `moves` consisting of the characters `'U'`, `'D'`, `'L'`, `'R'`, and `'_'`. + +Starting from the origin `(0, 0)`, each character represents one move on a 2D plane: + +* `'U'`: Move up by 1 unit. +* `'D'`: Move down by 1 unit. +* `'L'`: Move left by 1 unit. +* `'R'`: Move right by 1 unit. +* `'_'`: Can be independently replaced with any one of `'U'`, `'D'`, `'L'`, or `'R'`. + +Return the maximum **Manhattan distance** from the origin that can be achieved after all moves have been performed. + +**Example 1:** + +**Input:** moves = "L\_D\_" + +**Output:** 4 + +**Explanation:** + +One optimal choice is: + +* `'L'`: `(0, 0) -> (-1, 0)` +* `'_'` treated as `'D'`: `(-1, 0) -> (-1, -1)` +* `'D'`: `(-1, -1) -> (-1, -2)` +* `'_'` treated as `'L'`: `(-1, -2) -> (-2, -2)` + +The final Manhattan distance from the origin is `|0 - (-2)| + |0 - (-2)| = 4`. + +**Example 2:** + +**Input:** moves = "U\_R" + +**Output:** 3 + +**Explanation:** + +One optimal choice is: + +* `'U'`: `(0, 0) -> (0, 1)` +* `'_'` treated as `'U'`: `(0, 1) -> (0, 2)` +* `'R'`: `(0, 2) -> (1, 2)` + +The final Manhattan distance from the origin is `|0 - 1| + |0 - 2| = 3`. + +**Constraints:** + +* 1 <= moves.length <= 105 +* `moves` consists of only `'U'`, `'D'`, `'L'`, `'R'`, and `'_'`. \ No newline at end of file diff --git a/src/test/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/SolutionTest.java b/src/test/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/SolutionTest.java new file mode 100644 index 000000000..659589afc --- /dev/null +++ b/src/test/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3946_maximum_number_of_items_from_sale_i; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumSaleItems() { + assertThat( + new Solution().maximumSaleItems(new int[][] {{6, 2}, {2, 6}, {3, 4}}, 9), + equalTo(4)); + } + + @Test + void maximumSaleItems2() { + assertThat( + new Solution() + .maximumSaleItems(new int[][] {{2, 4}, {3, 2}, {4, 1}, {6, 4}, {12, 4}}, 8), + equalTo(10)); + } +} diff --git a/src/test/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/SolutionTest.java b/src/test/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/SolutionTest.java new file mode 100644 index 000000000..7f7f960db --- /dev/null +++ b/src/test/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/SolutionTest.java @@ -0,0 +1,25 @@ +package g3901_4000.s3947_maximum_number_of_items_from_sale_ii; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumSaleItems() { + assertThat( + new Solution().maximumSaleItems(new int[][] {{1, 6}, {2, 4}, {3, 5}}, 19), + equalTo(5)); + } + + @Test + void maximumSaleItems2() { + assertThat( + new Solution() + .maximumSaleItems( + new int[][] {{2, 8}, {1, 10}, {6, 6}, {4, 12}, {5, 20}, {5, 17}}, + 35), + equalTo(7)); + } +} diff --git a/src/test/java/g3901_4000/s3948_lexicographically_maximum_mex_array/SolutionTest.java b/src/test/java/g3901_4000/s3948_lexicographically_maximum_mex_array/SolutionTest.java new file mode 100644 index 000000000..e91dff146 --- /dev/null +++ b/src/test/java/g3901_4000/s3948_lexicographically_maximum_mex_array/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3948_lexicographically_maximum_mex_array; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumMEX() { + assertThat(new Solution().maximumMEX(new int[] {0, 1, 0}), equalTo(new int[] {2, 1})); + } + + @Test + void maximumMEX2() { + assertThat(new Solution().maximumMEX(new int[] {1, 0, 2}), equalTo(new int[] {3})); + } + + @Test + void maximumMEX3() { + assertThat(new Solution().maximumMEX(new int[] {3, 1}), equalTo(new int[] {0, 0})); + } +} diff --git a/src/test/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/SolutionTest.java b/src/test/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/SolutionTest.java new file mode 100644 index 000000000..2b5c89054 --- /dev/null +++ b/src/test/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/SolutionTest.java @@ -0,0 +1,18 @@ +package g3901_4000.s3950_exactly_one_consecutive_set_bits_pair; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void consecutiveSetBits() { + assertThat(new Solution().consecutiveSetBits(6), equalTo(true)); + } + + @Test + void consecutiveSetBits2() { + assertThat(new Solution().consecutiveSetBits(5), equalTo(false)); + } +} diff --git a/src/test/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/SolutionTest.java b/src/test/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/SolutionTest.java new file mode 100644 index 000000000..2ff5d82fc --- /dev/null +++ b/src/test/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3951_minimum_energy_to_maintain_brightness; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minEnergy() { + assertThat(new Solution().minEnergy(5, 5, new int[][] {{6, 12}}), equalTo(14L)); + } + + @Test + void minEnergy2() { + assertThat(new Solution().minEnergy(2, 1, new int[][] {{0, 0}, {2, 2}}), equalTo(2L)); + } + + @Test + void minEnergy3() { + assertThat(new Solution().minEnergy(4, 2, new int[][] {{1, 3}, {2, 4}}), equalTo(4L)); + } +} diff --git a/src/test/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/SolutionTest.java b/src/test/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/SolutionTest.java new file mode 100644 index 000000000..38b8d03e2 --- /dev/null +++ b/src/test/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3952_maximum_total_value_of_covered_indices; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxTotal() { + assertThat(new Solution().maxTotal(new int[] {9, 2, 6, 1}, "0101"), equalTo(15L)); + } + + @Test + void maxTotal2() { + assertThat(new Solution().maxTotal(new int[] {5, 1, 4}, "001"), equalTo(4L)); + } + + @Test + void maxTotal3() { + assertThat(new Solution().maxTotal(new int[] {9, 3, 5}, "011"), equalTo(14L)); + } +} diff --git a/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java b/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java new file mode 100644 index 000000000..8a4221522 --- /dev/null +++ b/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3953_maximum_score_with_co_prime_element; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxScore() { + assertThat(new Solution().maxScore(new int[] {3, 4, 6}, 5), equalTo(4)); + } + + @Test + void maxScore2() { + assertThat(new Solution().maxScore(new int[] {1, 2, 3}, 4), equalTo(3)); + } + + @Test + void maxScore3() { + assertThat(new Solution().maxScore(new int[] {2, 2}, 1), equalTo(1)); + } +} diff --git a/src/test/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/SolutionTest.java b/src/test/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/SolutionTest.java new file mode 100644 index 000000000..e4828256d --- /dev/null +++ b/src/test/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/SolutionTest.java @@ -0,0 +1,18 @@ +package g3901_4000.s3954_sum_of_compatible_numbers_in_range_i; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void sumOfGoodIntegers() { + assertThat(new Solution().sumOfGoodIntegers(2, 3), equalTo(10)); + } + + @Test + void sumOfGoodIntegers2() { + assertThat(new Solution().sumOfGoodIntegers(5, 1), equalTo(0)); + } +} diff --git a/src/test/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/SolutionTest.java b/src/test/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/SolutionTest.java new file mode 100644 index 000000000..62d1bc951 --- /dev/null +++ b/src/test/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/SolutionTest.java @@ -0,0 +1,21 @@ +package g3901_4000.s3955_valid_binary_strings_with_cost_limit; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void generateValidStrings() { + assertThat( + new Solution().generateValidStrings(3, 1), + equalTo(Arrays.asList("000", "010", "100"))); + } + + @Test + void generateValidStrings2() { + assertThat(new Solution().generateValidStrings(1, 0), equalTo(Arrays.asList("0", "1"))); + } +} diff --git a/src/test/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/SolutionTest.java b/src/test/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/SolutionTest.java new file mode 100644 index 000000000..5dfd28a9f --- /dev/null +++ b/src/test/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/SolutionTest.java @@ -0,0 +1,28 @@ +package g3901_4000.s3956_maximum_sum_of_m_non_overlapping_subarrays_i; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumSum() { + assertThat(new Solution().maximumSum(new int[] {4, 1, -5, 2}, 2, 1, 3), equalTo(7L)); + } + + @Test + void maximumSum2() { + assertThat(new Solution().maximumSum(new int[] {1, 0, 3, 4}, 2, 1, 2), equalTo(8L)); + } + + @Test + void maximumSum3() { + assertThat(new Solution().maximumSum(new int[] {-1, 7, -4}, 1, 2, 3), equalTo(6L)); + } + + @Test + void maximumSum4() { + assertThat(new Solution().maximumSum(new int[] {-3, -4, -1}, 2, 1, 2), equalTo(-1L)); + } +} diff --git a/src/test/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/SolutionTest.java b/src/test/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/SolutionTest.java new file mode 100644 index 000000000..01d649c00 --- /dev/null +++ b/src/test/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/SolutionTest.java @@ -0,0 +1,28 @@ +package g3901_4000.s3957_maximum_sum_of_m_non_overlapping_subarrays_ii; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumSum() { + assertThat(new Solution().maximumSum(new int[] {4, 1, -5, 2}, 2, 1, 3), equalTo(7L)); + } + + @Test + void maximumSum2() { + assertThat(new Solution().maximumSum(new int[] {1, 0, 3, 4}, 2, 1, 2), equalTo(8L)); + } + + @Test + void maximumSum3() { + assertThat(new Solution().maximumSum(new int[] {-1, 7, -4}, 1, 2, 3), equalTo(6L)); + } + + @Test + void maximumSum4() { + assertThat(new Solution().maximumSum(new int[] {-3, -4, -1}, 2, 1, 2), equalTo(-1L)); + } +} diff --git a/src/test/java/g3901_4000/s3959_check_good_integer/SolutionTest.java b/src/test/java/g3901_4000/s3959_check_good_integer/SolutionTest.java new file mode 100644 index 000000000..04e12ef27 --- /dev/null +++ b/src/test/java/g3901_4000/s3959_check_good_integer/SolutionTest.java @@ -0,0 +1,18 @@ +package g3901_4000.s3959_check_good_integer; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void checkGoodInteger() { + assertThat(new Solution().checkGoodInteger(1000), equalTo(false)); + } + + @Test + void checkGoodInteger2() { + assertThat(new Solution().checkGoodInteger(19), equalTo(true)); + } +} diff --git a/src/test/java/g3901_4000/s3960_frequency_balance_subarray/SolutionTest.java b/src/test/java/g3901_4000/s3960_frequency_balance_subarray/SolutionTest.java new file mode 100644 index 000000000..e1370e964 --- /dev/null +++ b/src/test/java/g3901_4000/s3960_frequency_balance_subarray/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3960_frequency_balance_subarray; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void getLength() { + assertThat(new Solution().getLength(new int[] {1, 2, 2, 1, 2, 3, 3, 3}), equalTo(5)); + } + + @Test + void getLength2() { + assertThat(new Solution().getLength(new int[] {5, 5, 5, 5}), equalTo(4)); + } + + @Test + void getLength3() { + assertThat(new Solution().getLength(new int[] {1, 2, 3, 4}), equalTo(1)); + } +} diff --git a/src/test/java/g3901_4000/s3961_maximize_sum_of_device_ratings/SolutionTest.java b/src/test/java/g3901_4000/s3961_maximize_sum_of_device_ratings/SolutionTest.java new file mode 100644 index 000000000..2c38aaa69 --- /dev/null +++ b/src/test/java/g3901_4000/s3961_maximize_sum_of_device_ratings/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3961_maximize_sum_of_device_ratings; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxRatings() { + assertThat(new Solution().maxRatings(new int[][] {{1, 3}, {2, 2}}), equalTo(4L)); + } + + @Test + void maxRatings2() { + assertThat(new Solution().maxRatings(new int[][] {{1, 2, 3}, {4, 5, 6}}), equalTo(6L)); + } + + @Test + void maxRatings3() { + assertThat(new Solution().maxRatings(new int[][] {{5, 5, 5}, {1, 1, 1}}), equalTo(6L)); + } +} diff --git a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java new file mode 100644 index 000000000..10f5506f8 --- /dev/null +++ b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3962_maximum_subarray_sum_after_at_most_k_swaps; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxSum() { + assertThat(new Solution().maxSum(new int[] {1, -1, 0, 2}, 1), equalTo(3L)); + } + + @Test + void maxSum2() { + assertThat(new Solution().maxSum(new int[] {4, 3, 2, 4}, 2), equalTo(13L)); + } + + @Test + void maxSum3() { + assertThat(new Solution().maxSum(new int[] {-1, -2}, 0), equalTo(-1L)); + } +} diff --git a/src/test/java/g3901_4000/s3963_create_grid_with_exactly_one_path/SolutionTest.java b/src/test/java/g3901_4000/s3963_create_grid_with_exactly_one_path/SolutionTest.java new file mode 100644 index 000000000..23b7b6993 --- /dev/null +++ b/src/test/java/g3901_4000/s3963_create_grid_with_exactly_one_path/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3963_create_grid_with_exactly_one_path; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void createGrid() { + assertThat(new Solution().createGrid(2, 3), equalTo(new String[] {"...", "##."})); + } + + @Test + void createGrid2() { + assertThat(new Solution().createGrid(3, 3), equalTo(new String[] {"...", "##.", "##."})); + } + + @Test + void createGrid3() { + assertThat(new Solution().createGrid(1, 4), equalTo(new String[] {"...."})); + } +} diff --git a/src/test/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/SolutionTest.java b/src/test/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/SolutionTest.java new file mode 100644 index 000000000..d697bf8c1 --- /dev/null +++ b/src/test/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/SolutionTest.java @@ -0,0 +1,18 @@ +package g3901_4000.s3964_minimum_lights_to_illuminate_a_road; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minLights() { + assertThat(new Solution().minLights(new int[] {0, 0, 0, 0}), equalTo(2)); + } + + @Test + void minLights2() { + assertThat(new Solution().minLights(new int[] {0, 0, 0, 2, 0}), equalTo(1)); + } +} diff --git a/src/test/java/g3901_4000/s3966_count_good_integers_in_a_range/SolutionTest.java b/src/test/java/g3901_4000/s3966_count_good_integers_in_a_range/SolutionTest.java new file mode 100644 index 000000000..c88fd87c4 --- /dev/null +++ b/src/test/java/g3901_4000/s3966_count_good_integers_in_a_range/SolutionTest.java @@ -0,0 +1,18 @@ +package g3901_4000.s3966_count_good_integers_in_a_range; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void goodIntegers() { + assertThat(new Solution().goodIntegers(10, 15, 1), equalTo(3L)); + } + + @Test + void goodIntegers2() { + assertThat(new Solution().goodIntegers(201, 204, 2), equalTo(2L)); + } +} diff --git a/src/test/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/SolutionTest.java b/src/test/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/SolutionTest.java new file mode 100644 index 000000000..499525ea9 --- /dev/null +++ b/src/test/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/SolutionTest.java @@ -0,0 +1,18 @@ +package g3901_4000.s3968_maximum_manhattan_distance_after_all_moves; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxDistance() { + assertThat(new Solution().maxDistance("L_D_"), equalTo(4)); + } + + @Test + void maxDistance2() { + assertThat(new Solution().maxDistance("U_R"), equalTo(3)); + } +} From ec4945906578a85cc35135bd52012f6b84c865e3 Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Wed, 21 Oct 2026 00:19:29 +0700 Subject: [PATCH 02/19] Update Solution.java --- .../Solution.java | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java index 0256db333..2a0bcd461 100644 --- a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java +++ b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java @@ -172,19 +172,29 @@ private long optimizeSwaps(int k, long sum, int minIndex, int maxOutside, SwapCo return result; } - private record SwapContext(int[] values, int[] included, int[] totalCounts) { + private static final class SwapContext { + private final int[] values; + private final int[] included; + private final int[] totalCounts; + + SwapContext(int[] values, int[] included, int[] totalCounts) { + this.values = values; + this.included = included; + this.totalCounts = totalCounts; + } @Override public boolean equals(Object obj) { if (this == obj) { return true; } - if (!(obj instanceof SwapContext(int[] values1, int[] included1, int[] counts))) { + if (!(obj instanceof SwapContext)) { return false; } - return Arrays.equals(values, values1) - && Arrays.equals(included, included1) - && Arrays.equals(totalCounts, counts); + SwapContext other = (SwapContext) obj; + return Arrays.equals(values, other.values) + && Arrays.equals(included, other.included) + && Arrays.equals(totalCounts, other.totalCounts); } @Override @@ -207,5 +217,15 @@ public String toString() { } } - private record PositiveInfo(int count, long sum, long maxElement) {} + private static final class PositiveInfo { + private final int count; + private final long sum; + private final long maxElement; + + PositiveInfo(int count, long sum, long maxElement) { + this.count = count; + this.sum = sum; + this.maxElement = maxElement; + } + } } From 37c332e74a3ba64a5b662a982d9a81e9ee074ca6 Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Wed, 21 Oct 2026 00:22:03 +0700 Subject: [PATCH 03/19] fix format --- .../Solution.java | 4 +++- .../Solution.java | 8 ++++---- .../Solution.java | 12 +++++++++--- .../Solution.java | 3 ++- 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java b/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java index 00098239a..8a05620d2 100644 --- a/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java +++ b/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java @@ -13,7 +13,9 @@ public long minEnergy(int n, int brightness, int[][] intervals) { int tot = 0; for (var a : intervals) { if (a[0] <= ed) { - if (a[1] > ed) ed = a[1]; + if (a[1] > ed) { + ed = a[1]; + } } else { tot += ed - st + 1; st = a[0]; diff --git a/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/Solution.java b/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/Solution.java index 62257ef53..508ce4962 100644 --- a/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/Solution.java +++ b/src/main/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/Solution.java @@ -4,13 +4,13 @@ // #2026_10_20_Time_8_ms_(93.94%)_Space_127.68_MB_(89.39%) public class Solution { - public long maxTotal(int[] A, String s) { - int n = A.length; + public long maxTotal(int[] nums, String s) { + int n = nums.length; int mn = 100000; long res = 0; for (int i = n - 1; i >= 0; --i) { - res += A[i]; - mn = Math.min(mn, A[i]); + res += nums[i]; + mn = Math.min(mn, nums[i]); if (s.charAt(i) == '0') { res -= mn; mn = 100000; diff --git a/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java b/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java index ca4767ae3..742ede965 100644 --- a/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java +++ b/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java @@ -18,7 +18,9 @@ public long maximumSum(int[] nums, int m, int l, int r) { this.l = l; this.r = r; pre = new long[n + 1]; - for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + nums[i]; + for (int i = 0; i < n; i++) { + pre[i + 1] = pre[i] + nums[i]; + } val = new long[n + 1]; cnt = new int[n + 1]; dq = new int[n + 2]; @@ -27,14 +29,18 @@ public long maximumSum(int[] nums, int m, int l, int r) { long hi = 20000000000L; long ansLambda = hi; solve(0); - if (cnt[n] <= m) return val[n]; + if (cnt[n] <= m) { + return val[n]; + } while (lo <= hi) { long mid = lo + (hi - lo) / 2; solve(mid); if (cnt[n] <= m) { ansLambda = mid; hi = mid - 1; - } else lo = mid + 1; + } else { + lo = mid + 1; + } } solve(ansLambda); return val[n] + ansLambda * m; diff --git a/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java b/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java index 5ea9ced27..4288e07f2 100644 --- a/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java +++ b/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java @@ -30,7 +30,7 @@ private long dfs(int index, int pre, int isLeadingZero, boolean isMaxDigit, int int maxDigit = isMaxDigit ? digits[index] : 9; long result = 0; for (int d = 0; d <= maxDigit; d++) { - if (isLeadingZero == 1 || Math.abs(d - pre) <= k) + if (isLeadingZero == 1 || Math.abs(d - pre) <= k) { result += dfs( index - 1, @@ -38,6 +38,7 @@ private long dfs(int index, int pre, int isLeadingZero, boolean isMaxDigit, int isLeadingZero == 1 && d == 0 ? 1 : 0, isMaxDigit && d == maxDigit, k); + } } if (!isMaxDigit) { DP[index][isLeadingZero][pre][k] = result; From df9e56a13f8ed84bc5493b5224e3f9db6f9d1b9f Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Wed, 21 Oct 2026 00:39:30 +0700 Subject: [PATCH 04/19] tests --- .../Solution.java | 3 +- .../Solution.java | 2 +- .../Solution.java | 8 +-- .../SolutionTest.java | 5 ++ .../SolutionTest.java | 7 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 10 +++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 10 +++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 64 +++++++++++++++++++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 5 ++ .../SolutionTest.java | 15 +++++ .../SolutionTest.java | 5 ++ 22 files changed, 183 insertions(+), 6 deletions(-) diff --git a/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java b/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java index 8a05620d2..3b94ff12e 100644 --- a/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java +++ b/src/main/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/Solution.java @@ -5,9 +5,10 @@ import java.util.Arrays; +@SuppressWarnings("java:S1172") public class Solution { public long minEnergy(int n, int brightness, int[][] intervals) { - Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); int st = 0; int ed = -1; int tot = 0; diff --git a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java index 2a0bcd461..49421b5b7 100644 --- a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java +++ b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java @@ -172,7 +172,7 @@ private long optimizeSwaps(int k, long sum, int minIndex, int maxOutside, SwapCo return result; } - private static final class SwapContext { + static final class SwapContext { private final int[] values; private final int[] included; private final int[] totalCounts; diff --git a/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java b/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java index 4288e07f2..ce14c3ccd 100644 --- a/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java +++ b/src/main/java/g3901_4000/s3966_count_good_integers_in_a_range/Solution.java @@ -4,7 +4,7 @@ // #2026_10_20_Time_3_ms_(100.00%)_Space_42.43_MB_(100.00%) public class Solution { - private static final Long[][][][] DP = new Long[16][2][10][10]; + private final Long[][][][] dp = new Long[16][2][10][10]; private final int[] digits = new int[16]; public long goodIntegers(long l, long r, int k) { @@ -24,8 +24,8 @@ private long dfs(int index, int pre, int isLeadingZero, boolean isMaxDigit, int if (index == -1) { return 1; } - if (!isMaxDigit && DP[index][isLeadingZero][pre][k] != null) { - return DP[index][isLeadingZero][pre][k]; + if (!isMaxDigit && dp[index][isLeadingZero][pre][k] != null) { + return dp[index][isLeadingZero][pre][k]; } int maxDigit = isMaxDigit ? digits[index] : 9; long result = 0; @@ -41,7 +41,7 @@ private long dfs(int index, int pre, int isLeadingZero, boolean isMaxDigit, int } } if (!isMaxDigit) { - DP[index][isLeadingZero][pre][k] = result; + dp[index][isLeadingZero][pre][k] = result; } return result; } diff --git a/src/test/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/SolutionTest.java b/src/test/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/SolutionTest.java index 659589afc..98aa2e1ea 100644 --- a/src/test/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/SolutionTest.java +++ b/src/test/java/g3901_4000/s3946_maximum_number_of_items_from_sale_i/SolutionTest.java @@ -20,4 +20,9 @@ void maximumSaleItems2() { .maximumSaleItems(new int[][] {{2, 4}, {3, 2}, {4, 1}, {6, 4}, {12, 4}}, 8), equalTo(10)); } + + @Test + void maximumSaleItems3() { + assertThat(new Solution().maximumSaleItems(new int[][] {{1, 1}}, 1), equalTo(1)); + } } diff --git a/src/test/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/SolutionTest.java b/src/test/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/SolutionTest.java index 7f7f960db..a3e18ae80 100644 --- a/src/test/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/SolutionTest.java +++ b/src/test/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/SolutionTest.java @@ -22,4 +22,11 @@ void maximumSaleItems2() { 35), equalTo(7)); } + + @Test + void maximumSaleItems3() { + assertThat( + new Solution().maximumSaleItems(new int[][] {{1, 6}, {2, 4}, {3, 5}}, 6), + equalTo(2)); + } } diff --git a/src/test/java/g3901_4000/s3948_lexicographically_maximum_mex_array/SolutionTest.java b/src/test/java/g3901_4000/s3948_lexicographically_maximum_mex_array/SolutionTest.java index e91dff146..6b65d4814 100644 --- a/src/test/java/g3901_4000/s3948_lexicographically_maximum_mex_array/SolutionTest.java +++ b/src/test/java/g3901_4000/s3948_lexicographically_maximum_mex_array/SolutionTest.java @@ -20,4 +20,9 @@ void maximumMEX2() { void maximumMEX3() { assertThat(new Solution().maximumMEX(new int[] {3, 1}), equalTo(new int[] {0, 0})); } + + @Test + void maximumMEX4() { + assertThat(new Solution().maximumMEX(new int[] {0}), equalTo(new int[] {1})); + } } diff --git a/src/test/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/SolutionTest.java b/src/test/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/SolutionTest.java index 2b5c89054..be78d1bb9 100644 --- a/src/test/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/SolutionTest.java +++ b/src/test/java/g3901_4000/s3950_exactly_one_consecutive_set_bits_pair/SolutionTest.java @@ -15,4 +15,9 @@ void consecutiveSetBits() { void consecutiveSetBits2() { assertThat(new Solution().consecutiveSetBits(5), equalTo(false)); } + + @Test + void consecutiveSetBits3() { + assertThat(new Solution().consecutiveSetBits(3), equalTo(true)); + } } diff --git a/src/test/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/SolutionTest.java b/src/test/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/SolutionTest.java index 2ff5d82fc..6aa916e8f 100644 --- a/src/test/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/SolutionTest.java +++ b/src/test/java/g3901_4000/s3951_minimum_energy_to_maintain_brightness/SolutionTest.java @@ -20,4 +20,9 @@ void minEnergy2() { void minEnergy3() { assertThat(new Solution().minEnergy(4, 2, new int[][] {{1, 3}, {2, 4}}), equalTo(4L)); } + + @Test + void minEnergy4() { + assertThat(new Solution().minEnergy(3, 1, new int[][] {{5, 6}, {0, 1}}), equalTo(4L)); + } } diff --git a/src/test/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/SolutionTest.java b/src/test/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/SolutionTest.java index 38b8d03e2..c39758e13 100644 --- a/src/test/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/SolutionTest.java +++ b/src/test/java/g3901_4000/s3952_maximum_total_value_of_covered_indices/SolutionTest.java @@ -20,4 +20,9 @@ void maxTotal2() { void maxTotal3() { assertThat(new Solution().maxTotal(new int[] {9, 3, 5}, "011"), equalTo(14L)); } + + @Test + void maxTotal4() { + assertThat(new Solution().maxTotal(new int[] {3}, "1"), equalTo(3L)); + } } diff --git a/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java b/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java index 8a4221522..81a78f03f 100644 --- a/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java +++ b/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java @@ -20,4 +20,14 @@ void maxScore2() { void maxScore3() { assertThat(new Solution().maxScore(new int[] {2, 2}, 1), equalTo(1)); } + + @Test + void maxScore4() { + assertThat(new Solution().maxScore(new int[] {4, 6}, 7), equalTo(6)); + } + + @Test + void maxScore5() { + assertThat(new Solution().maxScore(new int[] {10, 8}, 5), equalTo(5)); + } } diff --git a/src/test/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/SolutionTest.java b/src/test/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/SolutionTest.java index e4828256d..1145a59bf 100644 --- a/src/test/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/SolutionTest.java +++ b/src/test/java/g3901_4000/s3954_sum_of_compatible_numbers_in_range_i/SolutionTest.java @@ -15,4 +15,9 @@ void sumOfGoodIntegers() { void sumOfGoodIntegers2() { assertThat(new Solution().sumOfGoodIntegers(5, 1), equalTo(0)); } + + @Test + void sumOfGoodIntegers3() { + assertThat(new Solution().sumOfGoodIntegers(1, 1), equalTo(2)); + } } diff --git a/src/test/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/SolutionTest.java b/src/test/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/SolutionTest.java index 62d1bc951..31ba3057c 100644 --- a/src/test/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/SolutionTest.java +++ b/src/test/java/g3901_4000/s3955_valid_binary_strings_with_cost_limit/SolutionTest.java @@ -18,4 +18,9 @@ void generateValidStrings() { void generateValidStrings2() { assertThat(new Solution().generateValidStrings(1, 0), equalTo(Arrays.asList("0", "1"))); } + + @Test + void generateValidStrings3() { + assertThat(new Solution().generateValidStrings(2, 0), equalTo(Arrays.asList("00", "10"))); + } } diff --git a/src/test/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/SolutionTest.java b/src/test/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/SolutionTest.java index 5dfd28a9f..793c1afd0 100644 --- a/src/test/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/SolutionTest.java +++ b/src/test/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/SolutionTest.java @@ -25,4 +25,9 @@ void maximumSum3() { void maximumSum4() { assertThat(new Solution().maximumSum(new int[] {-3, -4, -1}, 2, 1, 2), equalTo(-1L)); } + + @Test + void maximumSum5() { + assertThat(new Solution().maximumSum(new int[] {1, 2, 3, 4, 5}, 2, 1, 1), equalTo(9L)); + } } diff --git a/src/test/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/SolutionTest.java b/src/test/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/SolutionTest.java index 01d649c00..348918852 100644 --- a/src/test/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/SolutionTest.java +++ b/src/test/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/SolutionTest.java @@ -25,4 +25,14 @@ void maximumSum3() { void maximumSum4() { assertThat(new Solution().maximumSum(new int[] {-3, -4, -1}, 2, 1, 2), equalTo(-1L)); } + + @Test + void maximumSum5() { + assertThat(new Solution().maximumSum(new int[] {1, 1, 1, 1, 1}, 1, 1, 1), equalTo(1L)); + } + + @Test + void maximumSum6() { + assertThat(new Solution().maximumSum(new int[] {1, 2, 3, 4, 5}, 2, 1, 1), equalTo(9L)); + } } diff --git a/src/test/java/g3901_4000/s3959_check_good_integer/SolutionTest.java b/src/test/java/g3901_4000/s3959_check_good_integer/SolutionTest.java index 04e12ef27..964d4247d 100644 --- a/src/test/java/g3901_4000/s3959_check_good_integer/SolutionTest.java +++ b/src/test/java/g3901_4000/s3959_check_good_integer/SolutionTest.java @@ -15,4 +15,9 @@ void checkGoodInteger() { void checkGoodInteger2() { assertThat(new Solution().checkGoodInteger(19), equalTo(true)); } + + @Test + void checkGoodInteger3() { + assertThat(new Solution().checkGoodInteger(99), equalTo(true)); + } } diff --git a/src/test/java/g3901_4000/s3960_frequency_balance_subarray/SolutionTest.java b/src/test/java/g3901_4000/s3960_frequency_balance_subarray/SolutionTest.java index e1370e964..adaaa50f4 100644 --- a/src/test/java/g3901_4000/s3960_frequency_balance_subarray/SolutionTest.java +++ b/src/test/java/g3901_4000/s3960_frequency_balance_subarray/SolutionTest.java @@ -20,4 +20,9 @@ void getLength2() { void getLength3() { assertThat(new Solution().getLength(new int[] {1, 2, 3, 4}), equalTo(1)); } + + @Test + void getLength4() { + assertThat(new Solution().getLength(new int[] {1, 1}), equalTo(2)); + } } diff --git a/src/test/java/g3901_4000/s3961_maximize_sum_of_device_ratings/SolutionTest.java b/src/test/java/g3901_4000/s3961_maximize_sum_of_device_ratings/SolutionTest.java index 2c38aaa69..6c4af33d4 100644 --- a/src/test/java/g3901_4000/s3961_maximize_sum_of_device_ratings/SolutionTest.java +++ b/src/test/java/g3901_4000/s3961_maximize_sum_of_device_ratings/SolutionTest.java @@ -20,4 +20,9 @@ void maxRatings2() { void maxRatings3() { assertThat(new Solution().maxRatings(new int[][] {{5, 5, 5}, {1, 1, 1}}), equalTo(6L)); } + + @Test + void maxRatings4() { + assertThat(new Solution().maxRatings(new int[][] {{4}, {7}, {1}}), equalTo(12L)); + } } diff --git a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java index 10f5506f8..6e7357e5b 100644 --- a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java +++ b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java @@ -20,4 +20,68 @@ void maxSum2() { void maxSum3() { assertThat(new Solution().maxSum(new int[] {-1, -2}, 0), equalTo(-1L)); } + + @Test + void maxSum4() { + assertThat(new Solution().maxSum(new int[] {-5, -1, -3}, 1), equalTo(-1L)); + } + + @Test + void maxSum5() { + assertThat( + new Solution().maxSum(new int[] {1, -10, 1, -10, 1, -10, 1}, 1), equalTo(3L)); + } + + @Test + void maxSum6() { + assertThat( + new Solution() + .maxSum(new int[] {10, -1000, 10, -1000, 10, -1000, 10, -1000, 10}, 1), + equalTo(30L)); + } + + @Test + void maxSum7() { + assertThat(new Solution().maxSum(new int[] {5, -1, -2, -3, 6}, 1), equalTo(11L)); + } + + @Test + void maxSum8() { + assertThat(new Solution().maxSum(new int[] {3, -5, 4, -5, 8}, 2), equalTo(15L)); + } + + @Test + void maxSum9() { + assertThat(new Solution().maxSum(new int[] {1, 1, 1, -100, 2}, 1), equalTo(5L)); + } + + @Test + void maxSum10() { + assertThat(new Solution().maxSum(new int[] {7}, 1), equalTo(7L)); + } + + @Test + void swapContext() { + Solution.SwapContext context = + new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {1, 1}); + assertThat(context.equals(context), equalTo(true)); + assertThat(context.equals(null), equalTo(false)); + assertThat(context.equals("swap"), equalTo(false)); + Solution.SwapContext same = + new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {1, 1}); + assertThat(context.equals(same), equalTo(true)); + assertThat(context.hashCode(), equalTo(same.hashCode())); + Solution.SwapContext differentValues = + new Solution.SwapContext(new int[] {1, 3}, new int[] {1, 0}, new int[] {1, 1}); + assertThat(context.equals(differentValues), equalTo(false)); + Solution.SwapContext differentIncluded = + new Solution.SwapContext(new int[] {1, 2}, new int[] {0, 1}, new int[] {1, 1}); + assertThat(context.equals(differentIncluded), equalTo(false)); + Solution.SwapContext differentCounts = + new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {2, 1}); + assertThat(context.equals(differentCounts), equalTo(false)); + assertThat( + context.toString(), + equalTo("SwapContext[values=[1, 2], included=[1, 0], totalCounts=[1, 1]]")); + } } diff --git a/src/test/java/g3901_4000/s3963_create_grid_with_exactly_one_path/SolutionTest.java b/src/test/java/g3901_4000/s3963_create_grid_with_exactly_one_path/SolutionTest.java index 23b7b6993..17cb68cdf 100644 --- a/src/test/java/g3901_4000/s3963_create_grid_with_exactly_one_path/SolutionTest.java +++ b/src/test/java/g3901_4000/s3963_create_grid_with_exactly_one_path/SolutionTest.java @@ -20,4 +20,9 @@ void createGrid2() { void createGrid3() { assertThat(new Solution().createGrid(1, 4), equalTo(new String[] {"...."})); } + + @Test + void createGrid4() { + assertThat(new Solution().createGrid(1, 1), equalTo(new String[] {"."})); + } } diff --git a/src/test/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/SolutionTest.java b/src/test/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/SolutionTest.java index d697bf8c1..61d49f2a2 100644 --- a/src/test/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/SolutionTest.java +++ b/src/test/java/g3901_4000/s3964_minimum_lights_to_illuminate_a_road/SolutionTest.java @@ -15,4 +15,9 @@ void minLights() { void minLights2() { assertThat(new Solution().minLights(new int[] {0, 0, 0, 2, 0}), equalTo(1)); } + + @Test + void minLights3() { + assertThat(new Solution().minLights(new int[] {1, 0}), equalTo(0)); + } } diff --git a/src/test/java/g3901_4000/s3966_count_good_integers_in_a_range/SolutionTest.java b/src/test/java/g3901_4000/s3966_count_good_integers_in_a_range/SolutionTest.java index c88fd87c4..320752e3b 100644 --- a/src/test/java/g3901_4000/s3966_count_good_integers_in_a_range/SolutionTest.java +++ b/src/test/java/g3901_4000/s3966_count_good_integers_in_a_range/SolutionTest.java @@ -15,4 +15,19 @@ void goodIntegers() { void goodIntegers2() { assertThat(new Solution().goodIntegers(201, 204, 2), equalTo(2L)); } + + @Test + void goodIntegers3() { + assertThat(new Solution().goodIntegers(10, 22, 0), equalTo(2L)); + } + + @Test + void goodIntegers4() { + assertThat(new Solution().goodIntegers(10, 10, 1), equalTo(1L)); + } + + @Test + void goodIntegers5() { + assertThat(new Solution().goodIntegers(10, 1000, 9), equalTo(991L)); + } } diff --git a/src/test/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/SolutionTest.java b/src/test/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/SolutionTest.java index 499525ea9..edc40ba4e 100644 --- a/src/test/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/SolutionTest.java +++ b/src/test/java/g3901_4000/s3968_maximum_manhattan_distance_after_all_moves/SolutionTest.java @@ -15,4 +15,9 @@ void maxDistance() { void maxDistance2() { assertThat(new Solution().maxDistance("U_R"), equalTo(3)); } + + @Test + void maxDistance3() { + assertThat(new Solution().maxDistance("UD"), equalTo(0)); + } } From 1b9a7a278faf42a17fd633516a3b3d7e1f5f1d5e Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Wed, 21 Oct 2026 00:43:05 +0700 Subject: [PATCH 05/19] Update SolutionTest.java --- .../SolutionTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java index 6e7357e5b..4b2405999 100644 --- a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java +++ b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java @@ -28,8 +28,7 @@ void maxSum4() { @Test void maxSum5() { - assertThat( - new Solution().maxSum(new int[] {1, -10, 1, -10, 1, -10, 1}, 1), equalTo(3L)); + assertThat(new Solution().maxSum(new int[] {1, -10, 1, -10, 1, -10, 1}, 1), equalTo(3L)); } @Test From c9e8a9c1b0941cc2fdcd5a0c8e2436ff7c4f1007 Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Wed, 21 Oct 2026 00:49:21 +0700 Subject: [PATCH 06/19] Update SolutionTest.java --- .../s3953_maximum_score_with_co_prime_element/SolutionTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java b/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java index 81a78f03f..a574c6c8f 100644 --- a/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java +++ b/src/test/java/g3901_4000/s3953_maximum_score_with_co_prime_element/SolutionTest.java @@ -28,6 +28,6 @@ void maxScore4() { @Test void maxScore5() { - assertThat(new Solution().maxScore(new int[] {10, 8}, 5), equalTo(5)); + assertThat(new Solution().maxScore(new int[] {10, 8}, 5), equalTo(9)); } } From 3033c8a24dd58807784d87b0fe1298aca4b5372e Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 21:57:15 +0300 Subject: [PATCH 07/19] Added task 3965 --- .../Solution.java | 56 ++++++++++++ .../s3965_finish_time_of_tasks_i/readme.md | 85 +++++++++++++++++++ .../SolutionTest.java | 22 +++++ 3 files changed, 163 insertions(+) create mode 100644 src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java create mode 100644 src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/readme.md create mode 100644 src/test/java/g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java diff --git a/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java b/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java new file mode 100644 index 000000000..afe435e29 --- /dev/null +++ b/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java @@ -0,0 +1,56 @@ +package g3901_4000.s3965_finish_time_of_tasks_i; + +// #Medium #Array #Dynamic_Programming #Tree #Staff #Depth_First_Search #Biweekly_Contest_185 + +public class Solution { + public long finishTime(int n, int[][] edges, int[] baseTime) { + int[][] torqavemi = edges; + int[] outDegree = new int[n]; + int[] parent = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = -1; + } + for (int[] edge : torqavemi) { + int u = edge[0]; + int v = edge[1]; + parent[v] = u; + outDegree[u]++; + } + long[] earliest = new long[n]; + long[] latest = new long[n]; + for (int i = 0; i < n; i++) { + earliest[i] = Long.MAX_VALUE; + latest[i] = Long.MIN_VALUE; + } + long[] finish = new long[n]; + int[] queue = new int[n]; + int head = 0, tail = 0; + for (int i = 0; i < n; i++) { + if (outDegree[i] == 0) { + queue[tail++] = i; + } + } + while (head < tail) { + int u = queue[head++]; + if (earliest[u] == Long.MAX_VALUE) { + finish[u] = baseTime[u]; + } else { + finish[u] = 2 * latest[u] - earliest[u] + baseTime[u]; + } + int p = parent[u]; + if (p != -1) { + if (finish[u] < earliest[p]) { + earliest[p] = finish[u]; + } + if (finish[u] > latest[p]) { + latest[p] = finish[u]; + } + outDegree[p]--; + if (outDegree[p] == 0) { + queue[tail++] = p; + } + } + } + return finish[0]; + } +} diff --git a/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/readme.md b/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/readme.md new file mode 100644 index 000000000..474447dc6 --- /dev/null +++ b/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/readme.md @@ -0,0 +1,85 @@ +3965\. Finish Time of Tasks I + +Medium + +You are given an integer `n` representing the number of tasks in a project, numbered from 0 to `n - 1`. These tasks are connected as a **tree** rooted at task 0. This is represented by a 2D integer array `edges` of length `n - 1`, where edges[i] = [ui, vi] indicates that task ui is the parent of task vi. + +You are also given an array `baseTime` of length `n`, where `baseTime[i]` represents the time to complete task `i`. + +The **finish time** of each task is calculated as follows: + +* Leaf task: The finish time is `baseTime[i]`. +* Non-leaf task: + * Let `earliest` be the **minimum** finish time among its children, and `latest` be the **maximum** finish time among its children. + * Let `ownDuration` be `(latest - earliest) + baseTime[i]`. + * The finish time of task `i` is `latest + ownDuration`. + +Return the finish time of the root task 0. + +**Example 1:** + +**Input:** n = 3, edges = [[0,1],[1,2]], baseTime = [9,5,3] + +**Output:** 17 + +**Explanation:** + +![](https://leetcode-images.github.io/g3901_4000/s3965_finish_time_of_tasks_i/picture1.png) + +* Task 2 is a leaf, so its finish time is `baseTime[2] = 3`. +* Task 1 has one child task 2: + * `earliest = latest = 3` + * `ownDuration = (latest - earliest) + baseTime[1] = 5` + * Finish time of task 1 is `3 + 5 = 8` +* Task 0 has one child with finish time 8: + * `earliest = latest = 8` + * `ownDuration = (latest - earliest) + baseTime[0] = 9` + * Finish time of task 0 is `8 + 9 = 17` + +**Example 2:** + +**Input:** n = 3, edges = [[0,1],[0,2]], baseTime = [4,7,6] + +**Output:** 12 + +**Explanation:** + +![](https://leetcode-images.github.io/g3901_4000/s3965_finish_time_of_tasks_i/picture2.png) + +* Task 1 is a leaf, so its finish time is `baseTime[1] = 7`. +* Task 2 is a leaf, so its finish time is `baseTime[2] = 6`. +* Task 0 has two children with finish times 7 and 6: + * `earliest = 6`, `latest = 7` + * `ownDuration = (latest - earliest) + baseTime[0] = (7 - 6) + 4 = 5` + * Finish time of task 0 is `latest + ownDuration = 7 + 5 = 12` + +**Example 3:** + +**Input:** n = 4, edges = [[0,1],[0,2],[2,3]], baseTime = [5,8,2,1] + +**Output:** 18 + +**Explanation:** + +* Task 1 is a leaf, so its finish time is `baseTime[1] = 8`. +* Task 3 is a leaf, so its finish time is `baseTime[3] = 1`. +* Task 2 has one child task 3: + * `earliest = latest = 1` + * `ownDuration = (latest - earliest) + baseTime[2] = 0 + 2 = 2` + * Finish time of task 2 is `latest + ownDuration = 1 + 2 = 3` +* Task 0 has two children with finish times 8 and 3: + * `earliest = 3`, `latest = 8` + * `ownDuration = (latest - earliest) + baseTime[0] = (8 - 3) + 5 = 10` + * Finish time of task 0 is `latest + ownDuration = 8 + 10 = 18` + +**Constraints:** + +* 1 <= n <= 105 +* `edges.length = n - 1` +* edges[i] == [ui, vi] +* 0 <= ui, vi <= n - 1 +* ui != vi +* The input is generated such that `edges` represents a valid tree. +* `baseTime.length == n` +* 1 <= baseTime[i] <= 105 +* The finish time of every task is guaranteed to be less than 253. \ No newline at end of file diff --git a/src/test/java/g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java b/src/test/java/g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java new file mode 100644 index 000000000..80131640a --- /dev/null +++ b/src/test/java/g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java @@ -0,0 +1,22 @@ +package g3901_4000.s3965_finish_time_of_tasks_i; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void finishTime() { + assertThat( + new Solution().finishTime(3, new int[][] {{0, 1}, {1, 2}}, new int[] {9, 5, 3}), + equalTo(17)); + } + + @Test + void finishTime2() { + assertThat( + new Solution().finishTime(3, new int[][] {{0, 1}, {0, 2}}, new int[] {4, 7, 6}), + equalTo(12)); + } +} From 0c005649a95438f1c43d1e92d64a4ae9f1786fbd Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 21:59:24 +0300 Subject: [PATCH 08/19] Fixed style --- .../java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java b/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java index afe435e29..9c307ab15 100644 --- a/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java +++ b/src/main/java/g3901_4000/s3965_finish_time_of_tasks_i/Solution.java @@ -24,7 +24,8 @@ public long finishTime(int n, int[][] edges, int[] baseTime) { } long[] finish = new long[n]; int[] queue = new int[n]; - int head = 0, tail = 0; + int head = 0; + int tail = 0; for (int i = 0; i < n; i++) { if (outDegree[i] == 0) { queue[tail++] = i; From 80818401f59f18801cc978435bf03ff46e1a29c8 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:01:17 +0300 Subject: [PATCH 09/19] Fixed tests --- .../g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java b/src/test/java/g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java index 80131640a..b0564f90b 100644 --- a/src/test/java/g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java +++ b/src/test/java/g3901_4000/s3965_finish_time_of_tasks_i/SolutionTest.java @@ -10,13 +10,13 @@ class SolutionTest { void finishTime() { assertThat( new Solution().finishTime(3, new int[][] {{0, 1}, {1, 2}}, new int[] {9, 5, 3}), - equalTo(17)); + equalTo(17L)); } @Test void finishTime2() { assertThat( new Solution().finishTime(3, new int[][] {{0, 1}, {0, 2}}, new int[] {4, 7, 6}), - equalTo(12)); + equalTo(12L)); } } From a6dcaea8fd9cf58162523766b9f3c3019db1c123 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:07:59 +0300 Subject: [PATCH 10/19] Refactor Solution.java by removing blank lines --- .../s3947_maximum_number_of_items_from_sale_ii/Solution.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/Solution.java b/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/Solution.java index b466f0582..6ac7c0984 100644 --- a/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/Solution.java +++ b/src/main/java/g3901_4000/s3947_maximum_number_of_items_from_sale_ii/Solution.java @@ -16,7 +16,6 @@ public int maximumSaleItems(int[][] items, int budget) { min = item[1]; } } - int[] temp = new int[n + 1]; for (int i = 1; i <= n; i++) { if (count[i] > 0) { @@ -27,7 +26,6 @@ public int maximumSaleItems(int[][] items, int budget) { temp[i] = m; } } - long[] deal = new long[n]; int dealcount = 0; long limit = min * 2; @@ -41,7 +39,6 @@ public int maximumSaleItems(int[][] items, int budget) { } } } - Arrays.sort(deal, 0, dealcount); long total = 0; for (int i = 0; i < dealcount; i++) { From d586b12ad6c4deb74e1e68696a9ca2081749530b Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:08:45 +0300 Subject: [PATCH 11/19] Refactor Solution.java for improved clarity and efficiency --- .../s3948_lexicographically_maximum_mex_array/Solution.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/Solution.java b/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/Solution.java index 3aa09ec9e..cb7b71073 100644 --- a/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/Solution.java +++ b/src/main/java/g3901_4000/s3948_lexicographically_maximum_mex_array/Solution.java @@ -9,7 +9,6 @@ public int[] maximumMEX(int[] nums) { int[] suffixMex = new int[n]; boolean[] seen = new boolean[n + 2]; int currMex = 0; - for (int i = n - 1; i >= 0; i--) { if (nums[i] < n + 2) { seen[nums[i]] = true; @@ -19,18 +18,14 @@ public int[] maximumMEX(int[] nums) { } suffixMex[i] = currMex; } - int[] result = new int[n]; int resIdx = 0; - int[] seenAtStep = new int[n + 2]; int stepCounter = 0; - int i = 0; while (i < n) { int m = suffixMex[i]; result[resIdx++] = m; - if (m == 0) { i++; } else { @@ -50,7 +45,6 @@ public int[] maximumMEX(int[] nums) { } } } - int[] finalResult = new int[resIdx]; System.arraycopy(result, 0, finalResult, 0, resIdx); return finalResult; From dee8fd29fab690b75f959302d780e365d781d98c Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:10:42 +0300 Subject: [PATCH 12/19] Refactor maxScore method and related logic --- .../Solution.java | 23 ------------------- 1 file changed, 23 deletions(-) diff --git a/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/Solution.java b/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/Solution.java index 67ebb9b30..fdf7097ac 100644 --- a/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/Solution.java +++ b/src/main/java/g3901_4000/s3953_maximum_score_with_co_prime_element/Solution.java @@ -7,12 +7,10 @@ import java.util.List; public class Solution { - public int maxScore(int[] nums, int maxVal) { int max = findMax(nums, maxVal); int[] cnt = countNumbers(nums, max); int[] groupCnt = buildGroupCounts(cnt, max); - int best = findBestAboveMaxVal(max, maxVal, cnt, groupCnt); return findBestWithinMaxVal(maxVal, cnt, groupCnt, best); } @@ -37,44 +35,35 @@ private int[] countNumbers(int[] nums, int max) { private int[] buildGroupCounts(int[] cnt, int max) { int[] groupCnt = new int[max + 1]; - for (int i = 1; i <= max; i++) { for (int j = 1; j * i <= max; j++) { groupCnt[i] += cnt[j * i]; } } - return groupCnt; } private int findBestAboveMaxVal(int max, int maxVal, int[] cnt, int[] groupCnt) { int best = -1; - for (int i = max; i > maxVal; i--) { if (cnt[i] == 0) { continue; } - int change = countConflict(i, groupCnt); best = Math.max(best, i - change + 1); } - return best; } private int findBestWithinMaxVal(int maxVal, int[] cnt, int[] groupCnt, int best) { - for (int i = maxVal; i > 0; i--) { if (best != -1 && i <= best) { break; } - int change = countConflict(i, groupCnt); change = adjustChange(i, change, cnt); - best = Math.max(best, i - change); } - return best; } @@ -82,11 +71,9 @@ private int adjustChange(int target, int change, int[] cnt) { if (change > 0 && cnt[target] != 0) { change--; } - if (change == 0 && cnt[target] == 0) { change++; } - return change; } @@ -94,28 +81,22 @@ private int countConflict(int target, int[] groupCnt) { List primeFactors = getFactor(target); int change = 0; int subsetCount = 1 << primeFactors.size(); - for (int mask = 1; mask < subsetCount; mask++) { change += calculateSubsetContribution(mask, primeFactors, groupCnt); } - return change; } private int calculateSubsetContribution(int mask, List primeFactors, int[] groupCnt) { - int product = 1; int bits = 0; - for (int k = 0; k < primeFactors.size(); k++) { if ((mask & (1 << k)) == 0) { continue; } - bits++; product *= primeFactors.get(k); } - int contribution = groupCnt[product]; return bits % 2 == 1 ? contribution : -contribution; } @@ -123,22 +104,18 @@ private int calculateSubsetContribution(int mask, List primeFactors, in private List getFactor(long number) { long n = number; List primeFactors = new ArrayList<>(); - for (int i = 2; i <= n / i; i++) { if (n % i != 0) { continue; } - primeFactors.add(i); while (n % i == 0) { n /= i; } } - if (n > 1) { primeFactors.add((int) n); } - return primeFactors; } } From cfbff0f8139ed79a99e403107595b8b487229c4c Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:12:03 +0300 Subject: [PATCH 13/19] Optimize maximum sum calculation logic --- .../Solution.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/Solution.java b/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/Solution.java index 165738307..1fafff3fb 100644 --- a/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/Solution.java +++ b/src/main/java/g3901_4000/s3956_maximum_sum_of_m_non_overlapping_subarrays_i/Solution.java @@ -41,22 +41,18 @@ public long maximumSum(int[] nums, int m, int l, int r) { } dq[tail++] = add; } - int left = i - r; while (head < tail && dq[head] < left) { head++; } - if (head < tail) { int s = dq[head]; curr[i] = Math.max(curr[i], pre[i] + prev[s] - pre[s]); } } - res = Math.max(res, curr[n]); prev = curr; } - return res; } } From 5cf004cff22a71dd15461065f453c2c778658bd0 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:13:18 +0300 Subject: [PATCH 14/19] Refactor solve method for maximum sum calculation --- .../Solution.java | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java b/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java index 742ede965..0b12bec49 100644 --- a/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java +++ b/src/main/java/g3901_4000/s3957_maximum_sum_of_m_non_overlapping_subarrays_ii/Solution.java @@ -24,7 +24,6 @@ public long maximumSum(int[] nums, int m, int l, int r) { val = new long[n + 1]; cnt = new int[n + 1]; dq = new int[n + 2]; - long lo = 0; long hi = 20000000000L; long ansLambda = hi; @@ -50,33 +49,25 @@ private void solve(long lambda) { final long neg = Long.MIN_VALUE / 4; val[0] = neg; cnt[0] = 0; - int head = 0; int tail = 0; - for (int i = 1; i <= n; i++) { int j = i - l; - if (j >= 0) { tail = addCandidate(j, head, tail); } - head = removeExpiredCandidates(head, tail, i - r); - long bestV = val[i - 1]; int bestC = cnt[i - 1]; - if (tail > head) { int b = dq[head]; long cand = normalizedValue(b) - pre[b] + pre[i] - lambda; int candC = normalizedCount(b) + 1; - if (isBetter(cand, candC, bestV, bestC)) { bestV = cand; bestC = candC; } } - val[i] = bestV; cnt[i] = bestC; } @@ -85,19 +76,16 @@ private void solve(long lambda) { private int addCandidate(int j, int head, int tail) { long key = normalizedValue(j) - pre[j]; int candidateCount = normalizedCount(j); - while (tail > head) { int t = dq[tail - 1]; long tailKey = normalizedValue(t) - pre[t]; int tailCount = normalizedCount(t); - if (tailKey < key || (tailKey == key && tailCount >= candidateCount)) { tail--; } else { break; } } - dq[tail++] = j; return tail; } From 6f8bbc4b280f2535eb191d426b2c320e72e463c1 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:18:40 +0300 Subject: [PATCH 15/19] Improved 3962 --- .../Solution.java | 288 +++++------------- 1 file changed, 81 insertions(+), 207 deletions(-) diff --git a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java index 49421b5b7..6d43e3b4e 100644 --- a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java +++ b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java @@ -1,231 +1,105 @@ package g3901_4000.s3962_maximum_subarray_sum_after_at_most_k_swaps; // #Hard #Array #Hash_Table #Sorting #Greedy #Heap_Priority_Queue #Ordered_Set #Binary_Indexed_Tree -// #Senior_Staff #Weekly_Contest_506 #2026_10_20_Time_13_ms_(98.61%)_Space_45.05_MB_(100.00%) +// #Senior_Staff #Weekly_Contest_506 #2026_10_20_Time_13_ms_(98.61%)_Space_44.94_MB_(100.00%) import java.util.Arrays; public class Solution { public long maxSum(int[] nums, int k) { + int n = nums.length; if (k == 0) { - return maxSubarraySum(nums); - } - PositiveInfo info = analyzePositiveValues(nums); - if (info.count == 0) { - return info.maxElement; - } - int maxPositiveWindow = findMaxPositiveWindow(nums, info.count); - if (k >= info.count - maxPositiveWindow) { - return info.sum; - } - int[] values = getUniqueSortedValues(nums); - int[] map = mapValues(nums, values); - int[] totalCounts = countMappedValues(map, values.length); - return findBestSum(nums, k, values, map, totalCounts); - } - - private long maxSubarraySum(int[] nums) { - long max = nums[0]; - long cur = nums[0]; - for (int i = 1; i < nums.length; i++) { - cur = Math.max(nums[i], cur + nums[i]); - max = Math.max(max, cur); + long max = nums[0], cur = nums[0]; + for (int i = 1; i < n; i++) { + cur = Math.max((long) nums[i], cur + nums[i]); + max = Math.max(max, cur); + } + return max; } - return max; - } - - private PositiveInfo analyzePositiveValues(int[] nums) { - int count = 0; - long sum = 0; - long maxElement = Long.MIN_VALUE; + int pc = 0; + int ps = 0; + long mele = Long.MIN_VALUE; for (int x : nums) { if (x > 0) { - sum += x; - count++; + ps += x; + pc++; } - maxElement = Math.max(maxElement, x); - } - return new PositiveInfo(count, sum, maxElement); - } - - private int findMaxPositiveWindow(int[] nums, int windowSize) { - int current = 0; - int max = 0; - for (int i = 0; i < nums.length; i++) { - if (nums[i] > 0) { - current++; - } - if (i >= windowSize && nums[i - windowSize] > 0) { - current--; - } - if (i >= windowSize - 1) { - max = Math.max(max, current); + if (x > mele) mele = x; + } + if (pc == 0) return mele; + int mpiw = 0, cpos = 0; + for (int i = 0; i < n; i++) { + if (nums[i] > 0) cpos++; + if (i >= pc && nums[i - pc] > 0) cpos--; + if (i >= pc - 1 && cpos > mpiw) { + mpiw = cpos; } } - return max; - } - - private int[] getUniqueSortedValues(int[] nums) { - int[] sorted = nums.clone(); - Arrays.sort(sorted); - int size = 0; - for (int x : sorted) { - if (size == 0 || sorted[size - 1] != x) { - sorted[size++] = x; - } + if (k >= pc - mpiw) { + return ps; } - return Arrays.copyOf(sorted, size); - } - - private int[] mapValues(int[] nums, int[] values) { - int[] map = new int[nums.length]; - for (int i = 0; i < nums.length; i++) { - map[i] = Arrays.binarySearch(values, nums[i]); - } - return map; - } - - private int[] countMappedValues(int[] map, int size) { - int[] counts = new int[size]; - for (int index : map) { - counts[index]++; - } - return counts; - } - - private long findBestSum(int[] nums, int k, int[] values, int[] map, int[] totalCounts) { - long best = Long.MIN_VALUE; - int[] included = new int[values.length]; - for (int i = 0; i < nums.length; i++) { - Arrays.fill(included, 0); - SwapContext context = new SwapContext(values, included, totalCounts); - best = evaluateStartingPosition(nums, i, k, map, context, best); - } - return best; - } - - private long evaluateStartingPosition( - int[] nums, int start, int k, int[] map, SwapContext context, long best) { - long sum = 0; - int minIndex = context.values.length; - int maxOutside = context.values.length - 1; - for (int j = start; j < nums.length; j++) { - int index = map[j]; - context.included[index]++; - sum += nums[j]; - minIndex = Math.min(minIndex, index); - maxOutside = findMaxOutside(maxOutside, context); - if (hasNoUsefulSwap(minIndex, maxOutside, context.values)) { - best = Math.max(best, sum); - } else if (sum + (long) k * (context.values[maxOutside] - context.values[minIndex]) - > best) { - long candidate = optimizeSwaps(k, sum, minIndex, maxOutside, context); - best = Math.max(best, candidate); + int[] v = new int[n]; + int[] s = nums.clone(); + Arrays.sort(s); + int m = 0; + for (int x : s) { + if (m == 0 || v[m - 1] != x) { + v[m++] = x; } } - return best; - } - - private int findMaxOutside(int maxOutside, SwapContext context) { - while (maxOutside >= 0 && context.totalCounts[maxOutside] == context.included[maxOutside]) { - maxOutside--; - } - return maxOutside; - } - - private boolean hasNoUsefulSwap(int minIndex, int maxOutside, int[] values) { - return maxOutside < 0 || values[minIndex] >= values[maxOutside]; - } - - private long optimizeSwaps(int k, long sum, int minIndex, int maxOutside, SwapContext context) { - int[] values = context.values; - int[] included = context.included; - int[] totalCounts = context.totalCounts; - long result = sum; - int swaps = 0; - int left = minIndex; - int right = maxOutside; - int leftCount = included[left]; - int rightCount = totalCounts[right] - included[right]; - - while (swaps < k && left < right) { - if (leftCount == 0) { - left++; - if (left < right) { - leftCount = included[left]; + int[] t = new int[m]; + int[] map = new int[n]; + for (int i = 0; i < n; i++) { + map[i] = Arrays.binarySearch(v, 0, m, nums[i]); + t[map[i]]++; + } + long ma = Long.MIN_VALUE; + int[] ife = new int[m]; + for (int i = 0; i < n; i++) { + Arrays.fill(ife, 0); + long sum = 0; + int mi = m; + int mo = m - 1; + for (int j = i; j < n; j++) { + int mid = map[j]; + ife[mid]++; + sum += nums[j]; + if (mid < mi) mi = mid; + while (mo >= 0 && t[mo] == ife[mo]) { + mo--; } - } else if (rightCount == 0) { - right--; - if (left < right) { - rightCount = totalCounts[right] - included[right]; + if (mo < 0 || v[mi] >= v[mo]) { + if (sum > ma) ma = sum; + continue; + } + if (sum + (long) k * (v[mo] - v[mi]) <= ma) { + continue; + } + long tsu = sum; + int swaps = 0; + int lp = mi; + int r = mo; + int inl = ife[lp], outr = r >= 0 ? t[r] - ife[r] : 0; + while (swaps < k && lp < r) { + if (inl == 0) { + inl = ife[++lp]; + } else if (outr == 0) { + if (--r >= 0) outr = t[r] - ife[r]; + } else if (v[lp] >= v[r]) { + break; + } else { + int take = Math.min(k - swaps, Math.min(inl, outr)); + tsu += (long) take * (v[r] - v[lp]); + swaps += take; + inl -= take; + outr -= take; + } + } + if (tsu > ma) { + ma = tsu; } - } else if (values[left] >= values[right]) { - break; - } else { - int take = Math.min(k - swaps, Math.min(leftCount, rightCount)); - result += (long) take * (values[right] - values[left]); - swaps += take; - leftCount -= take; - rightCount -= take; - } - } - return result; - } - - static final class SwapContext { - private final int[] values; - private final int[] included; - private final int[] totalCounts; - - SwapContext(int[] values, int[] included, int[] totalCounts) { - this.values = values; - this.included = included; - this.totalCounts = totalCounts; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof SwapContext)) { - return false; } - SwapContext other = (SwapContext) obj; - return Arrays.equals(values, other.values) - && Arrays.equals(included, other.included) - && Arrays.equals(totalCounts, other.totalCounts); - } - - @Override - public int hashCode() { - int result = Arrays.hashCode(values); - result = 31 * result + Arrays.hashCode(included); - result = 31 * result + Arrays.hashCode(totalCounts); - return result; - } - - @Override - public String toString() { - return "SwapContext[values=" - + Arrays.toString(values) - + ", included=" - + Arrays.toString(included) - + ", totalCounts=" - + Arrays.toString(totalCounts) - + "]"; - } - } - - private static final class PositiveInfo { - private final int count; - private final long sum; - private final long maxElement; - - PositiveInfo(int count, long sum, long maxElement) { - this.count = count; - this.sum = sum; - this.maxElement = maxElement; } + return ma; } } From f67303e9e0bff036843600ddee3c8370bb20c2de Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:22:28 +0300 Subject: [PATCH 16/19] Fixed test and style --- .../Solution.java | 9 ++++--- .../SolutionTest.java | 25 ------------------- 2 files changed, 6 insertions(+), 28 deletions(-) diff --git a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java index 6d43e3b4e..acbc7c3c4 100644 --- a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java +++ b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java @@ -9,7 +9,8 @@ public class Solution { public long maxSum(int[] nums, int k) { int n = nums.length; if (k == 0) { - long max = nums[0], cur = nums[0]; + long max = nums[0]; + long cur = nums[0]; for (int i = 1; i < n; i++) { cur = Math.max((long) nums[i], cur + nums[i]); max = Math.max(max, cur); @@ -27,7 +28,8 @@ public long maxSum(int[] nums, int k) { if (x > mele) mele = x; } if (pc == 0) return mele; - int mpiw = 0, cpos = 0; + int mpiw = 0; + int cpos = 0; for (int i = 0; i < n; i++) { if (nums[i] > 0) cpos++; if (i >= pc && nums[i - pc] > 0) cpos--; @@ -79,7 +81,8 @@ public long maxSum(int[] nums, int k) { int swaps = 0; int lp = mi; int r = mo; - int inl = ife[lp], outr = r >= 0 ? t[r] - ife[r] : 0; + int inl = ife[lp]; + int outr = r >= 0 ? t[r] - ife[r] : 0; while (swaps < k && lp < r) { if (inl == 0) { inl = ife[++lp]; diff --git a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java index 4b2405999..bab9475fc 100644 --- a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java +++ b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java @@ -58,29 +58,4 @@ void maxSum9() { void maxSum10() { assertThat(new Solution().maxSum(new int[] {7}, 1), equalTo(7L)); } - - @Test - void swapContext() { - Solution.SwapContext context = - new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {1, 1}); - assertThat(context.equals(context), equalTo(true)); - assertThat(context.equals(null), equalTo(false)); - assertThat(context.equals("swap"), equalTo(false)); - Solution.SwapContext same = - new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {1, 1}); - assertThat(context.equals(same), equalTo(true)); - assertThat(context.hashCode(), equalTo(same.hashCode())); - Solution.SwapContext differentValues = - new Solution.SwapContext(new int[] {1, 3}, new int[] {1, 0}, new int[] {1, 1}); - assertThat(context.equals(differentValues), equalTo(false)); - Solution.SwapContext differentIncluded = - new Solution.SwapContext(new int[] {1, 2}, new int[] {0, 1}, new int[] {1, 1}); - assertThat(context.equals(differentIncluded), equalTo(false)); - Solution.SwapContext differentCounts = - new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {2, 1}); - assertThat(context.equals(differentCounts), equalTo(false)); - assertThat( - context.toString(), - equalTo("SwapContext[values=[1, 2], included=[1, 0], totalCounts=[1, 1]]")); - } } From 0874aff3bcb7bbfd68d34eead981aa2660b9a19f Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:25:58 +0300 Subject: [PATCH 17/19] Fixed style --- .../Solution.java | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java index acbc7c3c4..75df47ef9 100644 --- a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java +++ b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java @@ -25,14 +25,22 @@ public long maxSum(int[] nums, int k) { ps += x; pc++; } - if (x > mele) mele = x; + if (x > mele) { + mele = x; + } + } + if (pc == 0) { + return mele; } - if (pc == 0) return mele; int mpiw = 0; int cpos = 0; for (int i = 0; i < n; i++) { - if (nums[i] > 0) cpos++; - if (i >= pc && nums[i - pc] > 0) cpos--; + if (nums[i] > 0) { + cpos++; + } + if (i >= pc && nums[i - pc] > 0) { + cpos--; + } if (i >= pc - 1 && cpos > mpiw) { mpiw = cpos; } @@ -66,12 +74,16 @@ public long maxSum(int[] nums, int k) { int mid = map[j]; ife[mid]++; sum += nums[j]; - if (mid < mi) mi = mid; + if (mid < mi) { + mi = mid; + } while (mo >= 0 && t[mo] == ife[mo]) { mo--; } if (mo < 0 || v[mi] >= v[mo]) { - if (sum > ma) ma = sum; + if (sum > ma) { + ma = sum; + } continue; } if (sum + (long) k * (v[mo] - v[mi]) <= ma) { @@ -87,7 +99,9 @@ public long maxSum(int[] nums, int k) { if (inl == 0) { inl = ife[++lp]; } else if (outr == 0) { - if (--r >= 0) outr = t[r] - ife[r]; + if (--r >= 0) { + outr = t[r] - ife[r]; + } } else if (v[lp] >= v[r]) { break; } else { From e6a00a1a210d414569d0591b26b29ccf24529ac0 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:28:05 +0300 Subject: [PATCH 18/19] Restored 3962 --- .../Solution.java | 297 ++++++++++++------ .../SolutionTest.java | 28 +- 2 files changed, 230 insertions(+), 95 deletions(-) diff --git a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java index 75df47ef9..49421b5b7 100644 --- a/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java +++ b/src/main/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/Solution.java @@ -1,122 +1,231 @@ package g3901_4000.s3962_maximum_subarray_sum_after_at_most_k_swaps; // #Hard #Array #Hash_Table #Sorting #Greedy #Heap_Priority_Queue #Ordered_Set #Binary_Indexed_Tree -// #Senior_Staff #Weekly_Contest_506 #2026_10_20_Time_13_ms_(98.61%)_Space_44.94_MB_(100.00%) +// #Senior_Staff #Weekly_Contest_506 #2026_10_20_Time_13_ms_(98.61%)_Space_45.05_MB_(100.00%) import java.util.Arrays; public class Solution { public long maxSum(int[] nums, int k) { - int n = nums.length; if (k == 0) { - long max = nums[0]; - long cur = nums[0]; - for (int i = 1; i < n; i++) { - cur = Math.max((long) nums[i], cur + nums[i]); - max = Math.max(max, cur); - } - return max; + return maxSubarraySum(nums); + } + PositiveInfo info = analyzePositiveValues(nums); + if (info.count == 0) { + return info.maxElement; } - int pc = 0; - int ps = 0; - long mele = Long.MIN_VALUE; + int maxPositiveWindow = findMaxPositiveWindow(nums, info.count); + if (k >= info.count - maxPositiveWindow) { + return info.sum; + } + int[] values = getUniqueSortedValues(nums); + int[] map = mapValues(nums, values); + int[] totalCounts = countMappedValues(map, values.length); + return findBestSum(nums, k, values, map, totalCounts); + } + + private long maxSubarraySum(int[] nums) { + long max = nums[0]; + long cur = nums[0]; + for (int i = 1; i < nums.length; i++) { + cur = Math.max(nums[i], cur + nums[i]); + max = Math.max(max, cur); + } + return max; + } + + private PositiveInfo analyzePositiveValues(int[] nums) { + int count = 0; + long sum = 0; + long maxElement = Long.MIN_VALUE; for (int x : nums) { if (x > 0) { - ps += x; - pc++; - } - if (x > mele) { - mele = x; + sum += x; + count++; } + maxElement = Math.max(maxElement, x); } - if (pc == 0) { - return mele; - } - int mpiw = 0; - int cpos = 0; - for (int i = 0; i < n; i++) { + return new PositiveInfo(count, sum, maxElement); + } + + private int findMaxPositiveWindow(int[] nums, int windowSize) { + int current = 0; + int max = 0; + for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { - cpos++; + current++; } - if (i >= pc && nums[i - pc] > 0) { - cpos--; + if (i >= windowSize && nums[i - windowSize] > 0) { + current--; } - if (i >= pc - 1 && cpos > mpiw) { - mpiw = cpos; + if (i >= windowSize - 1) { + max = Math.max(max, current); } } - if (k >= pc - mpiw) { - return ps; + return max; + } + + private int[] getUniqueSortedValues(int[] nums) { + int[] sorted = nums.clone(); + Arrays.sort(sorted); + int size = 0; + for (int x : sorted) { + if (size == 0 || sorted[size - 1] != x) { + sorted[size++] = x; + } + } + return Arrays.copyOf(sorted, size); + } + + private int[] mapValues(int[] nums, int[] values) { + int[] map = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { + map[i] = Arrays.binarySearch(values, nums[i]); + } + return map; + } + + private int[] countMappedValues(int[] map, int size) { + int[] counts = new int[size]; + for (int index : map) { + counts[index]++; } - int[] v = new int[n]; - int[] s = nums.clone(); - Arrays.sort(s); - int m = 0; - for (int x : s) { - if (m == 0 || v[m - 1] != x) { - v[m++] = x; + return counts; + } + + private long findBestSum(int[] nums, int k, int[] values, int[] map, int[] totalCounts) { + long best = Long.MIN_VALUE; + int[] included = new int[values.length]; + for (int i = 0; i < nums.length; i++) { + Arrays.fill(included, 0); + SwapContext context = new SwapContext(values, included, totalCounts); + best = evaluateStartingPosition(nums, i, k, map, context, best); + } + return best; + } + + private long evaluateStartingPosition( + int[] nums, int start, int k, int[] map, SwapContext context, long best) { + long sum = 0; + int minIndex = context.values.length; + int maxOutside = context.values.length - 1; + for (int j = start; j < nums.length; j++) { + int index = map[j]; + context.included[index]++; + sum += nums[j]; + minIndex = Math.min(minIndex, index); + maxOutside = findMaxOutside(maxOutside, context); + if (hasNoUsefulSwap(minIndex, maxOutside, context.values)) { + best = Math.max(best, sum); + } else if (sum + (long) k * (context.values[maxOutside] - context.values[minIndex]) + > best) { + long candidate = optimizeSwaps(k, sum, minIndex, maxOutside, context); + best = Math.max(best, candidate); } } - int[] t = new int[m]; - int[] map = new int[n]; - for (int i = 0; i < n; i++) { - map[i] = Arrays.binarySearch(v, 0, m, nums[i]); - t[map[i]]++; - } - long ma = Long.MIN_VALUE; - int[] ife = new int[m]; - for (int i = 0; i < n; i++) { - Arrays.fill(ife, 0); - long sum = 0; - int mi = m; - int mo = m - 1; - for (int j = i; j < n; j++) { - int mid = map[j]; - ife[mid]++; - sum += nums[j]; - if (mid < mi) { - mi = mid; - } - while (mo >= 0 && t[mo] == ife[mo]) { - mo--; - } - if (mo < 0 || v[mi] >= v[mo]) { - if (sum > ma) { - ma = sum; - } - continue; - } - if (sum + (long) k * (v[mo] - v[mi]) <= ma) { - continue; - } - long tsu = sum; - int swaps = 0; - int lp = mi; - int r = mo; - int inl = ife[lp]; - int outr = r >= 0 ? t[r] - ife[r] : 0; - while (swaps < k && lp < r) { - if (inl == 0) { - inl = ife[++lp]; - } else if (outr == 0) { - if (--r >= 0) { - outr = t[r] - ife[r]; - } - } else if (v[lp] >= v[r]) { - break; - } else { - int take = Math.min(k - swaps, Math.min(inl, outr)); - tsu += (long) take * (v[r] - v[lp]); - swaps += take; - inl -= take; - outr -= take; - } + return best; + } + + private int findMaxOutside(int maxOutside, SwapContext context) { + while (maxOutside >= 0 && context.totalCounts[maxOutside] == context.included[maxOutside]) { + maxOutside--; + } + return maxOutside; + } + + private boolean hasNoUsefulSwap(int minIndex, int maxOutside, int[] values) { + return maxOutside < 0 || values[minIndex] >= values[maxOutside]; + } + + private long optimizeSwaps(int k, long sum, int minIndex, int maxOutside, SwapContext context) { + int[] values = context.values; + int[] included = context.included; + int[] totalCounts = context.totalCounts; + long result = sum; + int swaps = 0; + int left = minIndex; + int right = maxOutside; + int leftCount = included[left]; + int rightCount = totalCounts[right] - included[right]; + + while (swaps < k && left < right) { + if (leftCount == 0) { + left++; + if (left < right) { + leftCount = included[left]; } - if (tsu > ma) { - ma = tsu; + } else if (rightCount == 0) { + right--; + if (left < right) { + rightCount = totalCounts[right] - included[right]; } + } else if (values[left] >= values[right]) { + break; + } else { + int take = Math.min(k - swaps, Math.min(leftCount, rightCount)); + result += (long) take * (values[right] - values[left]); + swaps += take; + leftCount -= take; + rightCount -= take; } } - return ma; + return result; + } + + static final class SwapContext { + private final int[] values; + private final int[] included; + private final int[] totalCounts; + + SwapContext(int[] values, int[] included, int[] totalCounts) { + this.values = values; + this.included = included; + this.totalCounts = totalCounts; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof SwapContext)) { + return false; + } + SwapContext other = (SwapContext) obj; + return Arrays.equals(values, other.values) + && Arrays.equals(included, other.included) + && Arrays.equals(totalCounts, other.totalCounts); + } + + @Override + public int hashCode() { + int result = Arrays.hashCode(values); + result = 31 * result + Arrays.hashCode(included); + result = 31 * result + Arrays.hashCode(totalCounts); + return result; + } + + @Override + public String toString() { + return "SwapContext[values=" + + Arrays.toString(values) + + ", included=" + + Arrays.toString(included) + + ", totalCounts=" + + Arrays.toString(totalCounts) + + "]"; + } + } + + private static final class PositiveInfo { + private final int count; + private final long sum; + private final long maxElement; + + PositiveInfo(int count, long sum, long maxElement) { + this.count = count; + this.sum = sum; + this.maxElement = maxElement; + } } } diff --git a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java index bab9475fc..6e7357e5b 100644 --- a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java +++ b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java @@ -28,7 +28,8 @@ void maxSum4() { @Test void maxSum5() { - assertThat(new Solution().maxSum(new int[] {1, -10, 1, -10, 1, -10, 1}, 1), equalTo(3L)); + assertThat( + new Solution().maxSum(new int[] {1, -10, 1, -10, 1, -10, 1}, 1), equalTo(3L)); } @Test @@ -58,4 +59,29 @@ void maxSum9() { void maxSum10() { assertThat(new Solution().maxSum(new int[] {7}, 1), equalTo(7L)); } + + @Test + void swapContext() { + Solution.SwapContext context = + new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {1, 1}); + assertThat(context.equals(context), equalTo(true)); + assertThat(context.equals(null), equalTo(false)); + assertThat(context.equals("swap"), equalTo(false)); + Solution.SwapContext same = + new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {1, 1}); + assertThat(context.equals(same), equalTo(true)); + assertThat(context.hashCode(), equalTo(same.hashCode())); + Solution.SwapContext differentValues = + new Solution.SwapContext(new int[] {1, 3}, new int[] {1, 0}, new int[] {1, 1}); + assertThat(context.equals(differentValues), equalTo(false)); + Solution.SwapContext differentIncluded = + new Solution.SwapContext(new int[] {1, 2}, new int[] {0, 1}, new int[] {1, 1}); + assertThat(context.equals(differentIncluded), equalTo(false)); + Solution.SwapContext differentCounts = + new Solution.SwapContext(new int[] {1, 2}, new int[] {1, 0}, new int[] {2, 1}); + assertThat(context.equals(differentCounts), equalTo(false)); + assertThat( + context.toString(), + equalTo("SwapContext[values=[1, 2], included=[1, 0], totalCounts=[1, 1]]")); + } } From 2cc4135d6deb4ae6699811a2d8dca8468981a32e Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 20 Oct 2026 22:30:14 +0300 Subject: [PATCH 19/19] Fixed format --- .../SolutionTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java index 6e7357e5b..4b2405999 100644 --- a/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java +++ b/src/test/java/g3901_4000/s3962_maximum_subarray_sum_after_at_most_k_swaps/SolutionTest.java @@ -28,8 +28,7 @@ void maxSum4() { @Test void maxSum5() { - assertThat( - new Solution().maxSum(new int[] {1, -10, 1, -10, 1, -10, 1}, 1), equalTo(3L)); + assertThat(new Solution().maxSum(new int[] {1, -10, 1, -10, 1, -10, 1}, 1), equalTo(3L)); } @Test