From b42453890d76babd6e5d2019da980ac065045b49 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Thu, 9 Jun 2022 08:40:35 +0300 Subject: [PATCH] Added tasks 2126-2241. --- README.md | 17 ++- .../s2126_destroying_asteroids/readme.md | 40 ++++-- .../readme.md | 73 +++++++++++ .../readme.md | 72 ++++++++++ .../s2157_groups_of_strings/readme.md | 123 ++++++++++++++++++ .../readme.md | 101 ++++++++++++++ .../readme.md | 92 +++++++++++++ .../readme.md | 104 +++++++++++++++ .../readme.md | 92 +++++++++++++ .../readme.md | 81 ++++++++++++ .../readme.md | 95 ++++++++++++++ .../readme.md | 57 ++++++++ .../readme.md | 47 +++++++ .../readme.md | 61 +++++++++ .../readme.md | 71 ++++++++++ .../readme.md | 116 +++++++++++++++++ .../s2241_design_an_atm_machine/readme.md | 102 +++++++++++++++ 17 files changed, 1334 insertions(+), 10 deletions(-) create mode 100644 src/main/java/g2101_2200/s2149_rearrange_array_elements_by_sign/readme.md create mode 100644 src/main/java/g2101_2200/s2156_find_substring_with_given_hash_value/readme.md create mode 100644 src/main/java/g2101_2200/s2157_groups_of_strings/readme.md create mode 100644 src/main/java/g2101_2200/s2163_minimum_difference_in_sums_after_removal_of_elements/readme.md create mode 100644 src/main/java/g2101_2200/s2167_minimum_time_to_remove_all_cars_containing_illegal_goods/readme.md create mode 100644 src/main/java/g2101_2200/s2170_minimum_operations_to_make_the_array_alternating/readme.md create mode 100644 src/main/java/g2101_2200/s2171_removing_minimum_number_of_magic_beans/readme.md create mode 100644 src/main/java/g2101_2200/s2178_maximum_split_of_positive_even_integers/readme.md create mode 100644 src/main/java/g2101_2200/s2179_count_good_triplets_in_an_array/readme.md create mode 100644 src/main/java/g2101_2200/s2180_count_integers_with_even_digit_sum/readme.md create mode 100644 src/main/java/g2101_2200/s2185_counting_words_with_a_given_prefix/readme.md create mode 100644 src/main/java/g2101_2200/s2186_minimum_number_of_steps_to_make_two_strings_anagram_ii/readme.md create mode 100644 src/main/java/g2201_2300/s2226_maximum_candies_allocated_to_k_children/readme.md create mode 100644 src/main/java/g2201_2300/s2234_maximum_total_beauty_of_the_gardens/readme.md create mode 100644 src/main/java/g2201_2300/s2241_design_an_atm_machine/readme.md diff --git a/README.md b/README.md index ce4955a7..9d0f0d4f 100644 --- a/README.md +++ b/README.md @@ -1332,6 +1332,9 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- | 2246 |[Longest Path With Different Adjacent Characters](src/main/java/g2201_2300/s2246_longest_path_with_different_adjacent_characters)| Hard | Array, String, Depth_First_Search, Tree, Graph, Topological_Sort | 75 | 97.79 +| 2241 |[Design an ATM Machine](src/main/java/g2201_2300/s2241_design_an_atm_machine)| Medium | Array, Greedy, Design | 192 | 24.16 +| 2234 |[Maximum Total Beauty of the Gardens](src/main/java/g2201_2300/s2234_maximum_total_beauty_of_the_gardens)| Hard | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 63 | 73.03 +| 2226 |[Maximum Candies Allocated to K Children](src/main/java/g2201_2300/s2226_maximum_candies_allocated_to_k_children)| Medium | Array, Binary_Search | 46 | 78.19 | 2200 |[Find All K-Distant Indices in an Array](src/main/java/g2101_2200/s2200_find_all_k_distant_indices_in_an_array)| Easy | Array | 2 | 95.30 | 2197 |[Replace Non-Coprime Numbers in Array](src/main/java/g2101_2200/s2197_replace_non_coprime_numbers_in_array)| Hard | Array, Math, Stack, Number_Theory | 60 | 85.52 | 2196 |[Create Binary Tree From Descriptions](src/main/java/g2101_2200/s2196_create_binary_tree_from_descriptions)| Medium | Array, Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 85 | 76.70 @@ -1343,23 +1346,35 @@ | 2190 |[Most Frequent Number Following Key In an Array](src/main/java/g2101_2200/s2190_most_frequent_number_following_key_in_an_array)| Easy | Array, Hash_Table, Counting | 1 | 100.00 | 2188 |[Minimum Time to Finish the Race](src/main/java/g2101_2200/s2188_minimum_time_to_finish_the_race)| Hard | Array, Dynamic_Programming | 15 | 93.69 | 2187 |[Minimum Time to Complete Trips](src/main/java/g2101_2200/s2187_minimum_time_to_complete_trips)| Medium | Array, Binary_Search | 187 | 95.03 +| 2186 |[Minimum Number of Steps to Make Two Strings Anagram II](src/main/java/g2101_2200/s2186_minimum_number_of_steps_to_make_two_strings_anagram_ii)| Medium | String, Hash_Table, Counting | 22 | 77.11 +| 2185 |[Counting Words With a Given Prefix](src/main/java/g2101_2200/s2185_counting_words_with_a_given_prefix)| Easy | Array, String | 0 | 100.00 | 2183 |[Count Array Pairs Divisible by K](src/main/java/g2101_2200/s2183_count_array_pairs_divisible_by_k)| Hard | Array, Math, Number_Theory | 849 | 44.54 | 2182 |[Construct String With Repeat Limit](src/main/java/g2101_2200/s2182_construct_string_with_repeat_limit)| Medium | String, Greedy, Heap_Priority_Queue, Counting | 26 | 96.11 | 2181 |[Merge Nodes in Between Zeros](src/main/java/g2101_2200/s2181_merge_nodes_in_between_zeros)| Medium | Simulation, Linked_List | 6 | 96.26 +| 2180 |[Count Integers With Even Digit Sum](src/main/java/g2101_2200/s2180_count_integers_with_even_digit_sum)| Easy | Math, Simulation | 0 | 100.00 +| 2179 |[Count Good Triplets in an Array](src/main/java/g2101_2200/s2179_count_good_triplets_in_an_array)| Hard | Array, Binary_Search, Ordered_Set, Divide_and_Conquer, Segment_Tree, Binary_Indexed_Tree, Merge_Sort | 16 | 92.94 +| 2178 |[Maximum Split of Positive Even Integers](src/main/java/g2101_2200/s2178_maximum_split_of_positive_even_integers)| Medium | Math, Greedy | 16 | 78.96 | 2177 |[Find Three Consecutive Integers That Sum to a Given Number](src/main/java/g2101_2200/s2177_find_three_consecutive_integers_that_sum_to_a_given_number)| Medium | Math, Simulation | 1 | 78.46 | 2176 |[Count Equal and Divisible Pairs in an Array](src/main/java/g2101_2200/s2176_count_equal_and_divisible_pairs_in_an_array)| Easy | Array | 4 | 78.29 | 2172 |[Maximum AND Sum of Array](src/main/java/g2101_2200/s2172_maximum_and_sum_of_array)| Hard | Array, Dynamic_Programming, Bit_Manipulation, Bitmask | 21 | 87.50 +| 2171 |[Removing Minimum Number of Magic Beans](src/main/java/g2101_2200/s2171_removing_minimum_number_of_magic_beans)| Medium | Array, Sorting, Prefix_Sum | 42 | 77.68 +| 2170 |[Minimum Operations to Make the Array Alternating](src/main/java/g2101_2200/s2170_minimum_operations_to_make_the_array_alternating)| Medium | Array, Hash_Table, Greedy, Counting | 8 | 100.00 | 2169 |[Count Operations to Obtain Zero](src/main/java/g2101_2200/s2169_count_operations_to_obtain_zero)| Easy | Math, Simulation | 0 | 100.00 +| 2167 |[Minimum Time to Remove All Cars Containing Illegal Goods](src/main/java/g2101_2200/s2167_minimum_time_to_remove_all_cars_containing_illegal_goods)| Hard | String, Dynamic_Programming | 46 | 61.00 | 2166 |[Design Bitset](src/main/java/g2101_2200/s2166_design_bitset)| Medium | Array, Hash_Table, Design | 81 | 73.38 | 2165 |[Smallest Value of the Rearranged Number](src/main/java/g2101_2200/s2165_smallest_value_of_the_rearranged_number)| Medium | Math, Sorting | 1 | 100.00 | 2164 |[Sort Even and Odd Indices Independently](src/main/java/g2101_2200/s2164_sort_even_and_odd_indices_independently)| Easy | Array, Sorting | 2 | 97.22 +| 2163 |[Minimum Difference in Sums After Removal of Elements](src/main/java/g2101_2200/s2163_minimum_difference_in_sums_after_removal_of_elements)| Hard | Array, Dynamic_Programming, Heap_Priority_Queue | 298 | 57.14 | 2162 |[Minimum Cost to Set Cooking Time](src/main/java/g2101_2200/s2162_minimum_cost_to_set_cooking_time)| Medium | Math, Enumeration | 1 | 95.82 | 2161 |[Partition Array According to Given Pivot](src/main/java/g2101_2200/s2161_partition_array_according_to_given_pivot)| Medium | Array, Two_Pointers, Simulation | 7 | 72.76 | 2160 |[Minimum Sum of Four Digit Number After Splitting Digits](src/main/java/g2101_2200/s2160_minimum_sum_of_four_digit_number_after_splitting_digits)| Easy | Math, Sorting, Greedy | 1 | 78.31 +| 2157 |[Groups of Strings](src/main/java/g2101_2200/s2157_groups_of_strings)| Hard | String, Bit_Manipulation, Union_Find | 451 | 93.86 +| 2156 |[Find Substring With Given Hash Value](src/main/java/g2101_2200/s2156_find_substring_with_given_hash_value)| Hard | String, Sliding_Window, Hash_Function, Rolling_Hash | 37 | 36.57 | 2155 |[All Divisions With the Highest Score of a Binary Array](src/main/java/g2101_2200/s2155_all_divisions_with_the_highest_score_of_a_binary_array)| Medium | Array | 18 | 98.41 | 2154 |[Keep Multiplying Found Values by Two](src/main/java/g2101_2200/s2154_keep_multiplying_found_values_by_two)| Easy | Array, Hash_Table, Sorting, Simulation | 1 | 93.21 | 2151 |[Maximum Good People Based on Statements](src/main/java/g2101_2200/s2151_maximum_good_people_based_on_statements)| Hard | Array, Bit_Manipulation, Backtracking, Enumeration | 76 | 47.57 | 2150 |[Find All Lonely Numbers in the Array](src/main/java/g2101_2200/s2150_find_all_lonely_numbers_in_the_array)| Medium | Array, Hash_Table, Counting | 93 | 70.66 +| 2149 |[Rearrange Array Elements by Sign](src/main/java/g2101_2200/s2149_rearrange_array_elements_by_sign)| Medium | Array, Two_Pointers, Simulation | 10 | 34.66 | 2148 |[Count Elements With Strictly Smaller and Greater Elements](src/main/java/g2101_2200/s2148_count_elements_with_strictly_smaller_and_greater_elements)| Easy | Array, Sorting | 0 | 100.00 | 2147 |[Number of Ways to Divide a Long Corridor](src/main/java/g2101_2200/s2147_number_of_ways_to_divide_a_long_corridor)| Hard | String, Dynamic_Programming, Math | 54 | 62.96 | 2146 |[K Highest Ranked Items Within a Price Range](src/main/java/g2101_2200/s2146_k_highest_ranked_items_within_a_price_range)| Medium | Array, Sorting, Breadth_First_Search, Matrix, Heap_Priority_Queue | 81 | 88.84 @@ -1378,7 +1393,7 @@ | 2130 |[Maximum Twin Sum of a Linked List](src/main/java/g2101_2200/s2130_maximum_twin_sum_of_a_linked_list)| Medium | Two_Pointers, Stack, Linked_List | 9 | 57.92 | 2129 |[Capitalize the Title](src/main/java/g2101_2200/s2129_capitalize_the_title)| Easy | String | 2 | 94.22 | 2127 |[Maximum Employees to Be Invited to a Meeting](src/main/java/g2101_2200/s2127_maximum_employees_to_be_invited_to_a_meeting)| Hard | Depth_First_Search, Graph, Topological_Sort | 37 | 85.71 -| 2126 |[Destroying Asteroids](src/main/java/g2101_2200/s2126_destroying_asteroids)| Medium | Array, Sorting, Greedy | 25 | 83.82 +| 2126 |[Destroying Asteroids](src/main/java/g2101_2200/s2126_destroying_asteroids)| Medium | Array, Sorting, Greedy | 6 | 99.27 | 2125 |[Number of Laser Beams in a Bank](src/main/java/g2101_2200/s2125_number_of_laser_beams_in_a_bank)| Medium | Array, String, Math, Matrix | 19 | 76.00 | 2124 |[Check if All A's Appears Before All B's](src/main/java/g2101_2200/s2124_check_if_all_as_appears_before_all_bs)| Easy | String | 1 | 73.82 | 2122 |[Recover the Original Array](src/main/java/g2101_2200/s2122_recover_the_original_array)| Hard | Array, Hash_Table, Sorting, Enumeration | 19 | 89.04 diff --git a/src/main/java/g2101_2200/s2126_destroying_asteroids/readme.md b/src/main/java/g2101_2200/s2126_destroying_asteroids/readme.md index a5f71e8f..4a3564ad 100644 --- a/src/main/java/g2101_2200/s2126_destroying_asteroids/readme.md +++ b/src/main/java/g2101_2200/s2126_destroying_asteroids/readme.md @@ -49,19 +49,41 @@ This is less than 23, so a collision would not destroy the last asteroid. ## Solution ```java -import java.util.Arrays; - public class Solution { public boolean asteroidsDestroyed(int mass, int[] asteroids) { - Arrays.sort(asteroids); - long m = mass; - for (int ele : asteroids) { - if (m < ele) { - return false; + return helper(mass, 0, asteroids); + } + + private boolean helper(long mass, int startIndex, int[] asteroids) { + int smallOrEqualIndex = partition(mass, startIndex, asteroids); + if (smallOrEqualIndex < startIndex) { + return false; + } + if (smallOrEqualIndex >= asteroids.length - 1) { + return true; + } + for (int i = startIndex; i <= smallOrEqualIndex; ++i) { + mass += asteroids[i]; + } + return helper(mass, ++smallOrEqualIndex, asteroids); + } + + private int partition(long mass, int startIndex, int[] asteroids) { + int length = asteroids.length; + int smallOrEqualIndex = startIndex - 1; + for (int i = startIndex; i < length; ++i) { + if (asteroids[i] <= mass) { + smallOrEqualIndex++; + swap(asteroids, i, smallOrEqualIndex); } - m += ele; } - return true; + return smallOrEqualIndex; + } + + private void swap(int[] array, int i, int j) { + int tmp = array[i]; + array[i] = array[j]; + array[j] = tmp; } } ``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2149_rearrange_array_elements_by_sign/readme.md b/src/main/java/g2101_2200/s2149_rearrange_array_elements_by_sign/readme.md new file mode 100644 index 00000000..5d6f5a26 --- /dev/null +++ b/src/main/java/g2101_2200/s2149_rearrange_array_elements_by_sign/readme.md @@ -0,0 +1,73 @@ +## 2149\. Rearrange Array Elements by Sign + +Medium + +You are given a **0-indexed** integer array `nums` of **even** length consisting of an **equal** number of positive and negative integers. + +You should **rearrange** the elements of `nums` such that the modified array follows the given conditions: + +1. Every **consecutive pair** of integers have **opposite signs**. +2. For all integers with the same sign, the **order** in which they were present in `nums` is **preserved**. +3. The rearranged array begins with a positive integer. + +Return _the modified array after rearranging the elements to satisfy the aforementioned conditions_. + +**Example 1:** + +**Input:** nums = [3,1,-2,-5,2,-4] + +**Output:** [3,-2,1,-5,2,-4] + +**Explanation:** The positive integers in nums are [3,1,2]. + +The negative integers are [-2,-5,-4]. + +The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4]. + +Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions. + +**Example 2:** + +**Input:** nums = [-1,1] + +**Output:** [1,-1] + +**Explanation:** 1 is the only positive integer and -1 the only negative integer in nums. + +So nums is rearranged to [1,-1]. + +**Constraints:** + +* 2 <= nums.length <= 2 * 105 +* `nums.length` is **even** +* 1 <= |nums[i]| <= 105 +* `nums` consists of **equal** number of positive and negative integers. + +## Solution + +```java +public class Solution { + public int[] rearrangeArray(int[] nums) { + int[] negatives = new int[nums.length / 2]; + int[] positives = new int[nums.length / 2]; + int[] result = new int[nums.length]; + int pPtr = 0; + int nPtr = 0; + int rPtr = 0; + for (int num : nums) { + if (num > 0) { + positives[pPtr++] = num; + } else { + negatives[nPtr++] = num; + } + } + pPtr = 0; + nPtr = 0; + while (pPtr < positives.length && nPtr < negatives.length) { + result[rPtr++] = positives[pPtr++]; + result[rPtr++] = negatives[nPtr++]; + } + return result; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2156_find_substring_with_given_hash_value/readme.md b/src/main/java/g2101_2200/s2156_find_substring_with_given_hash_value/readme.md new file mode 100644 index 00000000..c1cb0136 --- /dev/null +++ b/src/main/java/g2101_2200/s2156_find_substring_with_given_hash_value/readme.md @@ -0,0 +1,72 @@ +## 2156\. Find Substring With Given Hash Value + +Hard + +The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function: + +* hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. + +Where `val(s[i])` represents the index of `s[i]` in the alphabet from `val('a') = 1` to `val('z') = 26`. + +You are given a string `s` and the integers `power`, `modulo`, `k`, and `hashValue.` Return `sub`, _the **first** **substring** of_ `s` _of length_ `k` _such that_ `hash(sub, power, modulo) == hashValue`. + +The test cases will be generated such that an answer always **exists**. + +A **substring** is a contiguous non-empty sequence of characters within a string. + +**Example 1:** + +**Input:** s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0 + +**Output:** "ee" + +**Explanation:** The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 \* 1 + 5 \* 7) mod 20 = 40 mod 20 = 0. "ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee". + +**Example 2:** + +**Input:** s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32 + +**Output:** "fbx" + +**Explanation:** The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 \* 1 + 2 \* 31 + 24 \* 312) mod 100 = 23132 mod 100 = 32. + +The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 \* 1 + 24 \* 31 + 26 \* 312) mod 100 = 25732 mod 100 = 32. "fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx". + +Note that "bxz" also has a hash of 32 but it appears later than "fbx". + +**Constraints:** + +* 1 <= k <= s.length <= 2 * 104 +* 1 <= power, modulo <= 109 +* `0 <= hashValue < modulo` +* `s` consists of lowercase English letters only. +* The test cases are generated such that an answer always **exists**. + +## Solution + +```java +public class Solution { + public String subStrHash(String s, int power, int modulo, int k, int hashValue) { + long mul1 = 1; + int times = k - 1; + while (times-- > 0) { + mul1 = mul1 * power % modulo; + } + int index = -1; + long hash = 0; + int end = s.length() - 1; + for (int i = s.length() - 1; i >= 0; i--) { + int val = s.charAt(i) - 96; + hash = (hash * power % modulo + val) % modulo; + if (end - i + 1 == k) { + if (hash == hashValue) { + index = i; + } + hash = (hash - (s.charAt(end) - 96) * mul1 % modulo + modulo) % modulo; + end--; + } + } + return s.substring(index, index + k); + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2157_groups_of_strings/readme.md b/src/main/java/g2101_2200/s2157_groups_of_strings/readme.md new file mode 100644 index 00000000..052b1dbe --- /dev/null +++ b/src/main/java/g2101_2200/s2157_groups_of_strings/readme.md @@ -0,0 +1,123 @@ +## 2157\. Groups of Strings + +Hard + +You are given a **0-indexed** array of strings `words`. Each string consists of **lowercase English letters** only. No letter occurs more than once in any string of `words`. + +Two strings `s1` and `s2` are said to be **connected** if the set of letters of `s2` can be obtained from the set of letters of `s1` by any **one** of the following operations: + +* Adding exactly one letter to the set of the letters of `s1`. +* Deleting exactly one letter from the set of the letters of `s1`. +* Replacing exactly one letter from the set of the letters of `s1` with any letter, **including** itself. + +The array `words` can be divided into one or more non-intersecting **groups**. A string belongs to a group if any **one** of the following is true: + +* It is connected to **at least one** other string of the group. +* It is the **only** string present in the group. + +Note that the strings in `words` should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. + +Return _an array_ `ans` _of size_ `2` _where:_ + +* `ans[0]` _is the **maximum number** of groups_ `words` _can be divided into, and_ +* `ans[1]` _is the **size of the largest** group_. + +**Example 1:** + +**Input:** words = ["a","b","ab","cde"] + +**Output:** [2,3] + +**Explanation:** + +- words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2]. + +- words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2]. + +- words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1]. + +- words[3] is not connected to any string in words. + +Thus, words can be divided into 2 groups ["a","b","ab"] and ["cde"]. The size of the largest group is 3. + +**Example 2:** + +**Input:** words = ["a","ab","abc"] + +**Output:** [1,3] + +**Explanation:** + +- words[0] is connected to words[1]. + +- words[1] is connected to words[0] and words[2]. + +- words[2] is connected to words[1]. + +Since all strings are connected to each other, they should be grouped together. + +Thus, the size of the largest group is 3. + +**Constraints:** + +* 1 <= words.length <= 2 * 104 +* `1 <= words[i].length <= 26` +* `words[i]` consists of lowercase English letters only. +* No letter occurs more than once in `words[i]`. + +## Solution + +```java +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class Solution { + public int[] groupStrings(String[] words) { + HashMap map = new HashMap<>(); + for (String word : words) { + int bitmask = 0; + for (char ch : word.toCharArray()) { + bitmask |= (1 << (ch - 'a')); + } + map.put(bitmask, map.getOrDefault(bitmask, 0) + 1); + } + List keyset = new ArrayList<>(); + for (Integer key : map.keySet()) { + keyset.add(key); + } + int totalGroups = 0; + int maxSize = 0; + for (Integer key : keyset) { + if (!map.containsKey(key)) { + continue; + } + totalGroups++; + int size = dfs(key, map); + maxSize = Math.max(size, maxSize); + } + return new int[] {totalGroups, maxSize}; + } + + private int dfs(Integer key, HashMap map) { + if (!map.containsKey(key)) { + return 0; + } + int size = map.get(key); + map.remove(key); + for (int i = 0; i < 26; i++) { + size += dfs((key ^ (1 << i)), map); + } + for (int i = 0; i < 26; i++) { + if ((key & (1 << i)) > 0) { + for (int j = 0; j < 26; j++) { + if ((key & (1 << j)) == 0) { + size += dfs((key ^ (1 << i) ^ (1 << j)), map); + } + } + } + } + return size; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2163_minimum_difference_in_sums_after_removal_of_elements/readme.md b/src/main/java/g2101_2200/s2163_minimum_difference_in_sums_after_removal_of_elements/readme.md new file mode 100644 index 00000000..eaff37cb --- /dev/null +++ b/src/main/java/g2101_2200/s2163_minimum_difference_in_sums_after_removal_of_elements/readme.md @@ -0,0 +1,101 @@ +## 2163\. Minimum Difference in Sums After Removal of Elements + +Hard + +You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements. + +You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** parts: + +* The first `n` elements belonging to the first part and their sum is sumfirst. +* The next `n` elements belonging to the second part and their sum is sumsecond. + +The **difference in sums** of the two parts is denoted as sumfirst - sumsecond. + +* For example, if sumfirst = 3 and sumsecond = 2, their difference is `1`. +* Similarly, if sumfirst = 2 and sumsecond = 3, their difference is `-1`. + +Return _the **minimum difference** possible between the sums of the two parts after the removal of_ `n` _elements_. + +**Example 1:** + +**Input:** nums = [3,1,2] + +**Output:** -1 + +**Explanation:** Here, nums has 3 elements, so n = 1. + +Thus we have to remove 1 element from nums and divide the array into two equal parts. + +- If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1. + +- If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1. + +- If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2. + +The minimum difference between sums of the two parts is min(-1,1,2) = -1. + +**Example 2:** + +**Input:** nums = [7,9,5,8,1,3] + +**Output:** 1 + +**Explanation:** Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each. + +If we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12. + +To obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1. + +It can be shown that it is not possible to obtain a difference smaller than 1. + +**Constraints:** + +* `nums.length == 3 * n` +* 1 <= n <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```java +import java.util.PriorityQueue; + +public class Solution { + public long minimumDifference(int[] nums) { + int n = nums.length / 3; + PriorityQueue minHeap = new PriorityQueue<>(); + PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a); + long[] leftMemo = new long[nums.length]; + long[] rightMemo = new long[nums.length]; + long current = 0L; + for (int i = 0; i <= 2 * n - 1; i++) { + current += nums[i]; + maxHeap.add(nums[i]); + if (maxHeap.size() > n) { + int removed = maxHeap.poll(); + current -= removed; + leftMemo[i] = current; + } + if (maxHeap.size() == n) { + leftMemo[i] = current; + } + } + current = 0; + for (int i = nums.length - 1; i >= n; i--) { + current += nums[i]; + minHeap.add(nums[i]); + if (minHeap.size() > n) { + int removed = minHeap.poll(); + current -= removed; + } + if (minHeap.size() == n) { + rightMemo[i] = current; + } + } + long min = Long.MAX_VALUE; + for (int i = n - 1; i <= 2 * n - 1; i++) { + min = Math.min(min, leftMemo[i] - rightMemo[i + 1]); + } + return min; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2167_minimum_time_to_remove_all_cars_containing_illegal_goods/readme.md b/src/main/java/g2101_2200/s2167_minimum_time_to_remove_all_cars_containing_illegal_goods/readme.md new file mode 100644 index 00000000..0b9b1d35 --- /dev/null +++ b/src/main/java/g2101_2200/s2167_minimum_time_to_remove_all_cars_containing_illegal_goods/readme.md @@ -0,0 +1,92 @@ +## 2167\. Minimum Time to Remove All Cars Containing Illegal Goods + +Hard + +You are given a **0-indexed** binary string `s` which represents a sequence of train cars. `s[i] = '0'` denotes that the ith car does **not** contain illegal goods and `s[i] = '1'` denotes that the ith car does contain illegal goods. + +As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations **any** number of times: + +1. Remove a train car from the **left** end (i.e., remove `s[0]`) which takes 1 unit of time. +2. Remove a train car from the **right** end (i.e., remove `s[s.length - 1]`) which takes 1 unit of time. +3. Remove a train car from **anywhere** in the sequence which takes 2 units of time. + +Return _the **minimum** time to remove all the cars containing illegal goods_. + +Note that an empty sequence of cars is considered to have no cars containing illegal goods. + +**Example 1:** + +**Input:** s = "**11**00**1**0**1**" + +**Output:** 5 + +**Explanation:** + +One way to remove all the cars containing illegal goods from the sequence is to + +- remove a car from the left end 2 times. Time taken is 2 \* 1 = 2. + +- remove a car from the right end. Time taken is 1. + +- remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2 + 1 + 2 = 5. An alternative way is to + +- remove a car from the left end 2 times. Time taken is 2 \* 1 = 2. + +- remove a car from the right end 3 times. Time taken is 3 \* 1 = 3. This also obtains a total time of 2 + 3 = 5. + +5 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time. + +**Example 2:** + +**Input:** s = "00**1**0" + +**Output:** 2 + +**Explanation:** One way to remove all the cars containing illegal goods from the sequence is to + +- remove a car from the left end 3 times. Time taken is 3 \* 1 = 3. + +This obtains a total time of 3. + +Another way to remove all the cars containing illegal goods from the sequence is to + +- remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2. + +Another way to remove all the cars containing illegal goods from the sequence is to + +- remove a car from the right end 2 times. Time taken is 2 \* 1 = 2. + +This obtains a total time of 2. + +2 is the minimum time taken to remove all the cars containing illegal goods. + +There are no other ways to remove them with less time. + +**Constraints:** + +* 1 <= s.length <= 2 * 105 +* `s[i]` is either `'0'` or `'1'`. + +## Solution + +```java +public class Solution { + public int minimumTime(String s) { + final int n = s.length(); + int[] sum = new int[n + 1]; + for (int i = 0; i < n; ++i) { + sum[i + 1] = sum[i] + (s.charAt(i) - '0'); + } + if (sum[n] == 0) { + return 0; + } + int res = s.length(); + int min = Integer.MAX_VALUE; + for (int end = 0; end < n; ++end) { + min = Math.min(min, end - 2 * sum[end] + n - 1); + res = Math.min(res, min + 2 * sum[end + 1] - end); + } + return res; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2170_minimum_operations_to_make_the_array_alternating/readme.md b/src/main/java/g2101_2200/s2170_minimum_operations_to_make_the_array_alternating/readme.md new file mode 100644 index 00000000..86b4c2ee --- /dev/null +++ b/src/main/java/g2101_2200/s2170_minimum_operations_to_make_the_array_alternating/readme.md @@ -0,0 +1,104 @@ +## 2170\. Minimum Operations to Make the Array Alternating + +Medium + +You are given a **0-indexed** array `nums` consisting of `n` positive integers. + +The array `nums` is called **alternating** if: + +* `nums[i - 2] == nums[i]`, where `2 <= i <= n - 1`. +* `nums[i - 1] != nums[i]`, where `1 <= i <= n - 1`. + +In one **operation**, you can choose an index `i` and **change** `nums[i]` into **any** positive integer. + +Return _the **minimum number of operations** required to make the array alternating_. + +**Example 1:** + +**Input:** nums = [3,1,3,2,4,3] + +**Output:** 3 + +**Explanation:** + +One way to make the array alternating is by converting it to [3,1,3,**1**,**3**,**1**]. + +The number of operations required in this case is 3. + +It can be proven that it is not possible to make the array alternating in less than 3 operations. + +**Example 2:** + +**Input:** nums = [1,2,2,2,2] + +**Output:** 2 + +**Explanation:** + +One way to make the array alternating is by converting it to [1,2,**1**,2,**1**]. + +The number of operations required in this case is 2. + +Note that the array cannot be converted to [**2**,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```java +public class Solution { + public int minimumOperations(int[] nums) { + int maxOdd = 0; + int maxEven = 0; + int max = 0; + int n = nums.length; + for (int num : nums) { + max = Math.max(max, num); + } + int[] even = new int[max + 1]; + int[] odd = new int[max + 1]; + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + even[nums[i]]++; + } else { + odd[nums[i]]++; + } + } + int t1 = 0; + int t2 = 0; + for (int i = 0; i < max + 1; i++) { + if (even[i] > maxEven) { + maxEven = even[i]; + t1 = i; + } + if (odd[i] > maxOdd) { + maxOdd = odd[i]; + t2 = i; + } + } + int ans; + if (t1 == t2) { + int secondEven = 0; + int secondOdd = 0; + for (int i = 0; i < max + 1; i++) { + if (i != t1 && even[i] > secondEven) { + secondEven = even[i]; + } + if (i != t2 && odd[i] > secondOdd) { + secondOdd = odd[i]; + } + } + ans = + Math.min( + (n / 2 + n % 2 - maxEven) + (n / 2 - secondOdd), + (n / 2 + n % 2 - secondEven) + (n / 2 - maxOdd)); + } else { + ans = n / 2 + n % 2 - maxEven + n / 2 - maxOdd; + } + return ans; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2171_removing_minimum_number_of_magic_beans/readme.md b/src/main/java/g2101_2200/s2171_removing_minimum_number_of_magic_beans/readme.md new file mode 100644 index 00000000..2642f62e --- /dev/null +++ b/src/main/java/g2101_2200/s2171_removing_minimum_number_of_magic_beans/readme.md @@ -0,0 +1,92 @@ +## 2171\. Removing Minimum Number of Magic Beans + +Medium + +You are given an array of **positive** integers `beans`, where each integer represents the number of magic beans found in a particular magic bag. + +**Remove** any number of beans (**possibly none**) from each bag such that the number of beans in each remaining **non-empty** bag (still containing **at least one** bean) is **equal**. Once a bean has been removed from a bag, you are **not** allowed to return it to any of the bags. + +Return _the **minimum** number of magic beans that you have to remove_. + +**Example 1:** + +**Input:** beans = [4,**1**,6,5] + +**Output:** 4 + +**Explanation:** + +- We remove 1 bean from the bag with only 1 bean. + + This results in the remaining bags: [4,**0**,6,5] + +- Then we remove 2 beans from the bag with 6 beans. + + This results in the remaining bags: [4,0,**4**,5] + +- Then we remove 1 bean from the bag with 5 beans. + + This results in the remaining bags: [4,0,4,**4**] + +We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans. + +There are no other solutions that remove 4 beans or fewer. + +**Example 2:** + +**Input:** beans = [**2**,10,**3**,**2**] + +**Output:** 7 + +**Explanation:** + +- We remove 2 beans from one of the bags with 2 beans. + + This results in the remaining bags: [**0**,10,3,2] + +- Then we remove 2 beans from the other bag with 2 beans. + + This results in the remaining bags: [0,10,3,**0**] + +- Then we remove 3 beans from the bag with 3 beans. + + This results in the remaining bags: [0,10,**0**,0] + +We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans. + +There are no other solutions that removes 7 beans or fewer. + +**Constraints:** + +* 1 <= beans.length <= 105 +* 1 <= beans[i] <= 105 + +## Solution + +```java +import java.util.Arrays; + +public class Solution { + public long minimumRemoval(int[] beans) { + Arrays.sort(beans); + int n = beans.length; + long sum = 0; + for (int i = 0; i < n; i++) { + sum += beans[i]; + } + long minbeans = Long.MAX_VALUE; + long prefix = 0; + long suffix; + long count; + for (int i = 0; i < n; i++) { + prefix += beans[i]; + suffix = sum - prefix; + count = (prefix - beans[i]) + (suffix - beans[i] * (n - i - 1L)); + if (count < minbeans) { + minbeans = count; + } + } + return minbeans; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2178_maximum_split_of_positive_even_integers/readme.md b/src/main/java/g2101_2200/s2178_maximum_split_of_positive_even_integers/readme.md new file mode 100644 index 00000000..2f526e14 --- /dev/null +++ b/src/main/java/g2101_2200/s2178_maximum_split_of_positive_even_integers/readme.md @@ -0,0 +1,81 @@ +## 2178\. Maximum Split of Positive Even Integers + +Medium + +You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. + +* For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 + 4 + 6)` contains the maximum number of integers. Note that `finalSum` cannot be split into `(2 + 2 + 4 + 4)` as all the numbers should be unique. + +Return _a list of integers that represent a valid split containing a **maximum** number of integers_. If no valid split exists for `finalSum`, return _an **empty** list_. You may return the integers in **any** order. + +**Example 1:** + +**Input:** finalSum = 12 + +**Output:** [2,4,6] + +**Explanation:** The following are valid splits: `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. + +(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6]. + +Note that [2,6,4], [6,2,4], etc. are also accepted. + +**Example 2:** + +**Input:** finalSum = 7 + +**Output:** [] + +**Explanation:** There are no valid splits for the given finalSum. Thus, we return an empty array. + +**Example 3:** + +**Input:** finalSum = 28 + +**Output:** [6,8,2,12] + +**Explanation:** The following are valid splits: `(2 + 26)`, `(6 + 8 + 2 + 12)`, and `(4 + 24)`. + +`(6 + 8 + 2 + 12)` has the maximum number of integers, which is 4. Thus, we return [6,8,2,12]. + +Note that [10,2,4,12], [6,2,4,16], etc. are also accepted. + +**Constraints:** + +* 1 <= finalSum <= 1010 + +## Solution + +```java +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public List maximumEvenSplit(long finalSum) { + long curr = 2; + long remainingSum = finalSum; + List result = new ArrayList<>(); + if (finalSum % 2 != 0) { + return result; + } + while (remainingSum >= curr) { + result.add(curr); + remainingSum = remainingSum - curr; + curr += 2; + } + /* + go greedily by starting from smallest even number + for target = 16 after the while loop + remainingSum = 4 + curr = 8 (if we add 8 it exceeds the target 16) + result = [2,4,6] + so remove 6 from list and add it to remainigSum and insert to list + result = [2,4,10] + */ + long lastSum = result.get(result.size() - 1); + result.remove(result.size() - 1); + result.add(lastSum + remainingSum); + return result; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2179_count_good_triplets_in_an_array/readme.md b/src/main/java/g2101_2200/s2179_count_good_triplets_in_an_array/readme.md new file mode 100644 index 00000000..fc85041b --- /dev/null +++ b/src/main/java/g2101_2200/s2179_count_good_triplets_in_an_array/readme.md @@ -0,0 +1,95 @@ +## 2179\. Count Good Triplets in an Array + +Hard + +You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. + +A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2`. In other words, if we consider pos1v as the index of the value `v` in `nums1` and pos2v as the index of the value `v` in `nums2`, then a good triplet will be a set `(x, y, z)` where `0 <= x, y, z <= n - 1`, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. + +Return _the **total number** of good triplets_. + +**Example 1:** + +**Input:** nums1 = [2,0,1,3], nums2 = [0,1,2,3] + +**Output:** 1 + +**Explanation:** + +There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). + +Out of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. + +Hence, there is only 1 good triplet. + +**Example 2:** + +**Input:** nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3] + +**Output:** 4 + +**Explanation:** The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2). + +**Constraints:** + +* `n == nums1.length == nums2.length` +* 3 <= n <= 105 +* `0 <= nums1[i], nums2[i] <= n - 1` +* `nums1` and `nums2` are permutations of `[0, 1, ..., n - 1]`. + +## Solution + +```java +public class Solution { + public long goodTriplets(int[] nums1, int[] nums2) { + int n = nums1.length; + int[] idx = new int[n]; + int[] arr = new int[n]; + for (int i = 0; i < n; i++) { + idx[nums2[i]] = i; + } + for (int i = 0; i < n; i++) { + arr[i] = idx[nums1[i]]; + } + Tree tree = new Tree(n); + long res = 0L; + for (int i = 0; i < n; i++) { + int smaller = tree.query(arr[i]); + int bigger = n - (arr[i] + 1) - (i - smaller); + res += (long) smaller * bigger; + tree.update(arr[i] + 1, 1); + } + return res; + } + + private static class Tree { + int[] array; + int n; + + public Tree(int n) { + this.n = n; + array = new int[n + 1]; + } + + int lowbit(int x) { + return x & (-x); + } + + void update(int i, int delta) { + while (i <= n) { + array[i] += delta; + i += lowbit(i); + } + } + + int query(int k) { + int ans = 0; + while (k > 0) { + ans += array[k]; + k -= lowbit(k); + } + return ans; + } + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2180_count_integers_with_even_digit_sum/readme.md b/src/main/java/g2101_2200/s2180_count_integers_with_even_digit_sum/readme.md new file mode 100644 index 00000000..a4dddce7 --- /dev/null +++ b/src/main/java/g2101_2200/s2180_count_integers_with_even_digit_sum/readme.md @@ -0,0 +1,57 @@ +## 2180\. Count Integers With Even Digit Sum + +Easy + +Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. + +The **digit sum** of a positive integer is the sum of all its digits. + +**Example 1:** + +**Input:** num = 4 + +**Output:** 2 + +**Explanation:** + +The only integers less than or equal to 4 whose digit sums are even are 2 and 4. + +**Example 2:** + +**Input:** num = 30 + +**Output:** 14 + +**Explanation:** + +The 14 integers less than or equal to 30 whose digit sums are even are + +2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28. + +**Constraints:** + +* `1 <= num <= 1000` + +## Solution + +```java +public class Solution { + public int countEven(int n) { + if (n % 2 == 1) { + return n / 2; + } else { + int ans = 0; + int num = n; + while (num != 0) { + ans += num % 10; + num /= 10; + } + if (ans % 2 == 0) { + return n / 2; + } else { + return n / 2 - 1; + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2185_counting_words_with_a_given_prefix/readme.md b/src/main/java/g2101_2200/s2185_counting_words_with_a_given_prefix/readme.md new file mode 100644 index 00000000..caf07274 --- /dev/null +++ b/src/main/java/g2101_2200/s2185_counting_words_with_a_given_prefix/readme.md @@ -0,0 +1,47 @@ +## 2185\. Counting Words With a Given Prefix + +Easy + +You are given an array of strings `words` and a string `pref`. + +Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_. + +A **prefix** of a string `s` is any leading contiguous substring of `s`. + +**Example 1:** + +**Input:** words = ["pay","**at**tention","practice","**at**tend"], `pref` \= "at" + +**Output:** 2 + +**Explanation:** The 2 strings that contain "at" as a prefix are: "**at**tention" and "**at**tend". + +**Example 2:** + +**Input:** words = ["leetcode","win","loops","success"], `pref` \= "code" + +**Output:** 0 + +**Explanation:** There are no strings that contain "code" as a prefix. + +**Constraints:** + +* `1 <= words.length <= 100` +* `1 <= words[i].length, pref.length <= 100` +* `words[i]` and `pref` consist of lowercase English letters. + +## Solution + +```java +public class Solution { + public int prefixCount(String[] words, String pref) { + int count = 0; + for (String s : words) { + if (s.startsWith(pref)) { + count++; + } + } + return count; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2101_2200/s2186_minimum_number_of_steps_to_make_two_strings_anagram_ii/readme.md b/src/main/java/g2101_2200/s2186_minimum_number_of_steps_to_make_two_strings_anagram_ii/readme.md new file mode 100644 index 00000000..1e2665cc --- /dev/null +++ b/src/main/java/g2101_2200/s2186_minimum_number_of_steps_to_make_two_strings_anagram_ii/readme.md @@ -0,0 +1,61 @@ +## 2186\. Minimum Number of Steps to Make Two Strings Anagram II + +Medium + +You are given two strings `s` and `t`. In one step, you can append **any character** to either `s` or `t`. + +Return _the minimum number of steps to make_ `s` _and_ `t` _**anagrams** of each other._ + +An **anagram** of a string is a string that contains the same characters with a different (or the same) ordering. + +**Example 1:** + +**Input:** s = "**lee**tco**de**", t = "co**a**t**s**" + +**Output:** 7 + +**Explanation:** + +- In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcode**as**". + +- In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coats**leede**". + +"leetcodeas" and "coatsleede" are now anagrams of each other. + +We used a total of 2 + 5 = 7 steps. + +It can be shown that there is no way to make them anagrams of each other with less than 7 steps. + +**Example 2:** + +**Input:** s = "night", t = "thing" + +**Output:** 0 + +**Explanation:** The given strings are already anagrams of each other. Thus, we do not need any further steps. + +**Constraints:** + +* 1 <= s.length, t.length <= 2 * 105 +* `s` and `t` consist of lowercase English letters. + +## Solution + +```java +public class Solution { + public int minSteps(String s, String t) { + int[] a = new int[26]; + for (int i = 0; i < s.length(); i++) { + a[s.charAt(i) - 'a']++; + } + for (int i = 0; i < t.length(); i++) { + a[t.charAt(i) - 'a']--; + } + int sum = 0; + for (int j : a) { + sum += Math.abs(j); + } + return sum; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2201_2300/s2226_maximum_candies_allocated_to_k_children/readme.md b/src/main/java/g2201_2300/s2226_maximum_candies_allocated_to_k_children/readme.md new file mode 100644 index 00000000..fbd26fb2 --- /dev/null +++ b/src/main/java/g2201_2300/s2226_maximum_candies_allocated_to_k_children/readme.md @@ -0,0 +1,71 @@ +## 2226\. Maximum Candies Allocated to K Children + +Medium + +You are given a **0-indexed** integer array `candies`. Each element in the array denotes a pile of candies of size `candies[i]`. You can divide each pile into any number of **sub piles**, but you **cannot** merge two piles together. + +You are also given an integer `k`. You should allocate piles of candies to `k` children such that each child gets the **same** number of candies. Each child can take **at most one** pile of candies and some piles of candies may go unused. + +Return _the **maximum number of candies** each child can get._ + +**Example 1:** + +**Input:** candies = [5,8,6], k = 3 + +**Output:** 5 + +**Explanation:** We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies. + +**Example 2:** + +**Input:** candies = [2,5], k = 11 + +**Output:** 0 + +**Explanation:** There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0. + +**Constraints:** + +* 1 <= candies.length <= 105 +* 1 <= candies[i] <= 107 +* 1 <= k <= 1012 + +## Solution + +```java +public class Solution { + public int maximumCandies(int[] candies, long k) { + int max = Integer.MIN_VALUE; + long sum = 0; + for (int num : candies) { + max = Math.max(max, num); + sum += num; + } + if (sum < k) { + return 0; + } + int left = 1; + int right = max; + while (left < right) { + int mid = left + (right - left) / 2; + if (canBeDistributed(mid, candies, k)) { + if (!canBeDistributed(mid + 1, candies, k)) { + return mid; + } else { + left = mid + 1; + } + } else { + right = mid - 1; + } + } + return left; + } + + private boolean canBeDistributed(int num, int[] candies, long k) { + for (int i = 0; i < candies.length && k > 0; ++i) { + k -= candies[i] / num; + } + return k <= 0; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2201_2300/s2234_maximum_total_beauty_of_the_gardens/readme.md b/src/main/java/g2201_2300/s2234_maximum_total_beauty_of_the_gardens/readme.md new file mode 100644 index 00000000..bc14284e --- /dev/null +++ b/src/main/java/g2201_2300/s2234_maximum_total_beauty_of_the_gardens/readme.md @@ -0,0 +1,116 @@ +## 2234\. Maximum Total Beauty of the Gardens + +Hard + +Alice is a caretaker of `n` gardens and she wants to plant flowers to maximize the total beauty of all her gardens. + +You are given a **0-indexed** integer array `flowers` of size `n`, where `flowers[i]` is the number of flowers already planted in the ith garden. Flowers that are already planted **cannot** be removed. You are then given another integer `newFlowers`, which is the **maximum** number of flowers that Alice can additionally plant. You are also given the integers `target`, `full`, and `partial`. + +A garden is considered **complete** if it has **at least** `target` flowers. The **total beauty** of the gardens is then determined as the **sum** of the following: + +* The number of **complete** gardens multiplied by `full`. +* The **minimum** number of flowers in any of the **incomplete** gardens multiplied by `partial`. If there are no incomplete gardens, then this value will be `0`. + +Return _the **maximum** total beauty that Alice can obtain after planting at most_ `newFlowers` _flowers._ + +**Example 1:** + +**Input:** flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1 + +**Output:** 14 + +**Explanation:** Alice can plant + +- 2 flowers in the 0th garden + +- 3 flowers in the 1st garden + +- 1 flower in the 2nd garden + +- 1 flower in the 3rd garden + +The gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers. + +There is 1 garden that is complete. + +The minimum number of flowers in the incomplete gardens is 2. + +Thus, the total beauty is 1 \* 12 + 2 \* 1 = 12 + 2 = 14. + +No other way of planting flowers can obtain a total beauty higher than 14. + +**Example 2:** + +**Input:** flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6 + +**Output:** 30 + +**Explanation:** Alice can plant + +- 3 flowers in the 0th garden + +- 0 flowers in the 1st garden + +- 0 flowers in the 2nd garden + +- 2 flowers in the 3rd garden + +The gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers. + +There are 3 gardens that are complete. + +The minimum number of flowers in the incomplete gardens is 4. + +Thus, the total beauty is 3 \* 2 + 4 \* 6 = 6 + 24 = 30. + +No other way of planting flowers can obtain a total beauty higher than 30. + +Note that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty. + +**Constraints:** + +* 1 <= flowers.length <= 105 +* 1 <= flowers[i], target <= 105 +* 1 <= newFlowers <= 1010 +* 1 <= full, partial <= 105 + +## Solution + +```java +import java.util.Arrays; + +public class Solution { + public long maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) { + int n = flowers.length; + long[] prefix = new long[n + 1]; + Arrays.sort(flowers); + for (int i = 0; i < n; ++i) { + prefix[i + 1] = prefix[i] + Math.min(flowers[i], target); + } + long res = 0; + int i = n - 1; + for (int c = 0; c <= n; ++c) { + long remain = prefix[n] - prefix[n - c] + newFlowers - c * (long) target; + long min = 0; + if (0 > remain) { + break; + } + i = Math.min(i, n - c - 1); + while (0 <= i + && (target <= flowers[i] + || flowers[i] * (long) (i + 1) - prefix[i + 1] > remain)) { + i--; + } + if (0 <= i) { + long dif = flowers[i] * (long) (i + 1) - prefix[i + 1]; + min = Math.min(target - 1L, flowers[i] + (remain - dif) / (i + 1)); + if (i + 1 < n - c) { + min = Math.min(min, flowers[i + 1]); + } + } + res = Math.max(res, c * (long) full + min * partial); + } + return res; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2201_2300/s2241_design_an_atm_machine/readme.md b/src/main/java/g2201_2300/s2241_design_an_atm_machine/readme.md new file mode 100644 index 00000000..bc42ebbd --- /dev/null +++ b/src/main/java/g2201_2300/s2241_design_an_atm_machine/readme.md @@ -0,0 +1,102 @@ +## 2241\. Design an ATM Machine + +Medium + +There is an ATM machine that stores banknotes of `5` denominations: `20`, `50`, `100`, `200`, and `500` dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. + +When withdrawing, the machine prioritizes using banknotes of **larger** values. + +* For example, if you want to withdraw `$300` and there are `2` `$50` banknotes, `1` `$100` banknote, and `1` `$200` banknote, then the machine will use the `$100` and `$200` banknotes. +* However, if you try to withdraw `$600` and there are `3` `$200` banknotes and `1` `$500` banknote, then the withdraw request will be rejected because the machine will first try to use the `$500` banknote and then be unable to use banknotes to complete the remaining `$100`. Note that the machine is **not** allowed to use the `$200` banknotes instead of the `$500` banknote. + +Implement the ATM class: + +* `ATM()` Initializes the ATM object. +* `void deposit(int[] banknotesCount)` Deposits new banknotes in the order `$20`, `$50`, `$100`, `$200`, and `$500`. +* `int[] withdraw(int amount)` Returns an array of length `5` of the number of banknotes that will be handed to the user in the order `$20`, `$50`, `$100`, `$200`, and `$500`, and update the number of banknotes in the ATM after withdrawing. Returns `[-1]` if it is not possible (do **not** withdraw any banknotes in this case). + +**Example 1:** + +**Input** + +["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"] + +[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]] + +**Output:** [null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]] + +**Explanation:** + + ATM atm = new ATM(); + atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes, + // and 1 $500 banknote. + atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote + // and 1 $500 banknote. The banknotes left over in the + // machine are [0,0,0,2,0]. + atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote. + // The banknotes in the machine are now [0,1,0,3,1]. + atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote + // and then be unable to complete the remaining $100, + // so the withdraw request will be rejected. + // Since the request is rejected, the number of banknotes + // in the machine is not modified. + atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote + // and 1 $500 banknote. + +**Constraints:** + +* `banknotesCount.length == 5` +* 0 <= banknotesCount[i] <= 109 +* 1 <= amount <= 109 +* At most `5000` calls **in total** will be made to `withdraw` and `deposit`. +* At least **one** call will be made to each function `withdraw` and `deposit`. + +## Solution + +```java +public class ATM { + private int[] nominals; + private long[] counts; + + public ATM() { + nominals = new int[] {20, 50, 100, 200, 500}; + counts = new long[5]; + } + + public void deposit(int[] banknotesCount) { + for (int i = 0; i < 5; i++) { + counts[i] += banknotesCount[i]; + } + } + + public int[] withdraw(int amount) { + int[] delivery = new int[5]; + long currentAmount = amount; + for (int i = 4; i >= 0; i--) { + if (currentAmount > nominals[i] * counts[i]) { + delivery[i] = (int) counts[i]; + } else { + delivery[i] = (int) currentAmount / nominals[i]; + } + currentAmount += (long) -nominals[i] * delivery[i]; + if (currentAmount == 0) { + break; + } + } + if (currentAmount > 0) { + return new int[] {-1}; + } + for (int i = 0; i < 5; i++) { + counts[i] += -delivery[i]; + } + return delivery; + } +} + +/* + * Your ATM object will be instantiated and called as such: + * ATM obj = new ATM(); + * obj.deposit(banknotesCount); + * int[] param_2 = obj.withdraw(amount); + */ +``` \ No newline at end of file