diff --git a/README.md b/README.md index 3c230267..f2eb5c48 100644 --- a/README.md +++ b/README.md @@ -1816,7 +1816,32 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- -| 2824 |[Count Pairs Whose Sum is Less than Target](src/main/kotlin/g2801_2900/s2824_count_pairs_whose_sum_is_less_than_target)| Easy | Array, Sorting | s | s +| 2856 |[Minimum Array Length After Pair Removals](src/main/kotlin/g2801_2900/s2856_minimum_array_length_after_pair_removals)| Medium | Array, Hash_Table, Greedy, Binary_Search, Two_Pointers, Counting | 647 | 100.00 +| 2855 |[Minimum Right Shifts to Sort the Array](src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array)| Easy | Array | 169 | 75.00 +| 2851 |[String Transformation](src/main/kotlin/g2801_2900/s2851_string_transformation)| Hard | String, Dynamic_Programming, Math, String_Matching | 377 | 100.00 +| 2850 |[Minimum Moves to Spread Stones Over Grid](src/main/kotlin/g2801_2900/s2850_minimum_moves_to_spread_stones_over_grid)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix | 133 | 100.00 +| 2849 |[Determine if a Cell Is Reachable at a Given Time](src/main/kotlin/g2801_2900/s2849_determine_if_a_cell_is_reachable_at_a_given_time)| Medium | Math | 138 | 80.95 +| 2848 |[Points That Intersect With Cars](src/main/kotlin/g2801_2900/s2848_points_that_intersect_with_cars)| Easy | Hash_Table, Math, Prefix_Sum | 190 | 100.00 +| 2846 |[Minimum Edge Weight Equilibrium Queries in a Tree](src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree)| Hard | Array, Tree, Graph, Strongly_Connected_Component | 982 | 100.00 +| 2845 |[Count of Interesting Subarrays](src/main/kotlin/g2801_2900/s2845_count_of_interesting_subarrays)| Medium | Array, Hash_Table, Prefix_Sum | 703 | 100.00 +| 2844 |[Minimum Operations to Make a Special Number](src/main/kotlin/g2801_2900/s2844_minimum_operations_to_make_a_special_number)| Medium | String, Math, Greedy, Enumeration | 162 | 60.00 +| 2843 |[Count Symmetric Integers](src/main/kotlin/g2801_2900/s2843_count_symmetric_integers)| Easy | Math, Enumeration | 203 | 88.24 +| 2842 |[Count K-Subsequences of a String With Maximum Beauty](src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty)| Hard | String, Hash_Table, Math, Greedy, Combinatorics | 217 | 100.00 +| 2841 |[Maximum Sum of Almost Unique Subarray](src/main/kotlin/g2801_2900/s2841_maximum_sum_of_almost_unique_subarray)| Medium | Array, Hash_Table, Sliding_Window | 387 | 100.00 +| 2840 |[Check if Strings Can be Made Equal With Operations II](src/main/kotlin/g2801_2900/s2840_check_if_strings_can_be_made_equal_with_operations_ii)| Medium | String, Hash_Table, Sorting | 225 | 100.00 +| 2839 |[Check if Strings Can be Made Equal With Operations I](src/main/kotlin/g2801_2900/s2839_check_if_strings_can_be_made_equal_with_operations_i)| Easy | String | 154 | 100.00 +| 2836 |[Maximize Value of Function in a Ball Passing Game](src/main/kotlin/g2801_2900/s2836_maximize_value_of_function_in_a_ball_passing_game)| Hard | Array, Dynamic_Programming, Bit_Manipulation | 933 | 100.00 +| 2835 |[Minimum Operations to Form Subsequence With Target Sum](src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum)| Hard | Array, Greedy, Bit_Manipulation | 183 | 100.00 +| 2834 |[Find the Minimum Possible Sum of a Beautiful Array](src/main/kotlin/g2801_2900/s2834_find_the_minimum_possible_sum_of_a_beautiful_array)| Medium | Math, Greedy | 130 | 100.00 +| 2833 |[Furthest Point From Origin](src/main/kotlin/g2801_2900/s2833_furthest_point_from_origin)| Easy | Array, Counting | 160 | 81.25 +| 2831 |[Find the Longest Equal Subarray](src/main/kotlin/g2801_2900/s2831_find_the_longest_equal_subarray)| Medium | Array, Hash_Table, Binary_Search, Sliding_Window | 663 | 100.00 +| 2830 |[Maximize the Profit as the Salesman](src/main/kotlin/g2801_2900/s2830_maximize_the_profit_as_the_salesman)| Medium | Array, Dynamic_Programming, Sorting, Binary_Search | 776 | 100.00 +| 2829 |[Determine the Minimum Sum of a k-avoiding Array](src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array)| Medium | Math, Greedy | 162 | 75.00 +| 2828 |[Check if a String Is an Acronym of Words](src/main/kotlin/g2801_2900/s2828_check_if_a_string_is_an_acronym_of_words)| Easy | Array, String | 180 | 90.14 +| 2827 |[Number of Beautiful Integers in the Range](src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range)| Hard | Dynamic_Programming, Math | 169 | 100.00 +| 2826 |[Sorting Three Groups](src/main/kotlin/g2801_2900/s2826_sorting_three_groups)| Medium | Array, Dynamic_Programming | 250 | 100.00 +| 2825 |[Make String a Subsequence Using Cyclic Increments](src/main/kotlin/g2801_2900/s2825_make_string_a_subsequence_using_cyclic_increments)| Medium | String, Two_Pointers | 227 | 83.33 +| 2824 |[Count Pairs Whose Sum is Less than Target](src/main/kotlin/g2801_2900/s2824_count_pairs_whose_sum_is_less_than_target)| Easy | Array, Sorting, Two_Pointers | 168 | 90.62 | 2818 |[Apply Operations to Maximize Score](src/main/kotlin/g2801_2900/s2818_apply_operations_to_maximize_score)| Hard | Array, Math, Greedy, Stack, Monotonic_Stack, Number_Theory | 727 | 100.00 | 2817 |[Minimum Absolute Difference Between Elements With Constraint](src/main/kotlin/g2801_2900/s2817_minimum_absolute_difference_between_elements_with_constraint)| Medium | Array, Binary_Search, Ordered_Set | 759 | 100.00 | 2816 |[Double a Number Represented as a Linked List](src/main/kotlin/g2801_2900/s2816_double_a_number_represented_as_a_linked_list)| Medium | Math, Stack, Linked_List | 393 | 100.00 diff --git a/src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/readme.md b/src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/readme.md index b0b330ed..36bf1205 100644 --- a/src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/readme.md +++ b/src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/readme.md @@ -53,7 +53,7 @@ class Solution { return target.size - longestIncreasingSubsequence(list) } - private fun longestIncreasingSubsequence(list: MutableList): Int { + private fun longestIncreasingSubsequence(list: List): Int { val n = list.size var l = 0 val arr = IntArray(n) diff --git a/src/main/kotlin/g2301_2400/s2306_naming_a_company/readme.md b/src/main/kotlin/g2301_2400/s2306_naming_a_company/readme.md index f437152a..0fd9a7bd 100644 --- a/src/main/kotlin/g2301_2400/s2306_naming_a_company/readme.md +++ b/src/main/kotlin/g2301_2400/s2306_naming_a_company/readme.md @@ -85,11 +85,10 @@ class Solution { res += compare(b1, b2) } } - return res } - fun compare(b1: MutableSet, b2: MutableSet): Long { + fun compare(b1: Set, b2: Set): Long { val set1 = if (b1.size > b2.size) b1 else b2 val set2 = if (b1.size > b2.size) b2 else b1 var n1 = set1.size @@ -100,7 +99,6 @@ class Solution { n2-- } } - return (n1 * n2) * 2L } } diff --git a/src/main/kotlin/g2801_2900/s2825_make_string_a_subsequence_using_cyclic_increments/readme.md b/src/main/kotlin/g2801_2900/s2825_make_string_a_subsequence_using_cyclic_increments/readme.md new file mode 100644 index 00000000..a3954d19 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2825_make_string_a_subsequence_using_cyclic_increments/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2825\. Make String a Subsequence Using Cyclic Increments + +Medium + +You are given two **0-indexed** strings `str1` and `str2`. + +In an operation, you select a **set** of indices in `str1`, and for each index `i` in the set, increment `str1[i]` to the next character **cyclically**. That is `'a'` becomes `'b'`, `'b'` becomes `'c'`, and so on, and `'z'` becomes `'a'`. + +Return `true` _if it is possible to make_ `str2` _a subsequence of_ `str1` _by performing the operation **at most once**_, _and_ `false` _otherwise_. + +**Note:** A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters. + +**Example 1:** + +**Input:** str1 = "abc", str2 = "ad" + +**Output:** true + +**Explanation:** Select index 2 in str1. Increment str1[2] to become 'd'. Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned. + +**Example 2:** + +**Input:** str1 = "zc", str2 = "ad" + +**Output:** true + +**Explanation:** Select indices 0 and 1 in str1. Increment str1[0] to become 'a'. Increment str1[1] to become 'd'. Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned. + +**Example 3:** + +**Input:** str1 = "ab", str2 = "d" + +**Output:** false + +**Explanation:** In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once. Therefore, false is returned. + +**Constraints:** + +* 1 <= str1.length <= 105 +* 1 <= str2.length <= 105 +* `str1` and `str2` consist of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun canMakeSubsequence(str1: String, str2: String): Boolean { + var str1ptr = 0 + for (element in str2) { + val c2 = element + var found = false + while (str1ptr < str1.length) { + val c1 = str1[str1ptr++] + if (c1 == c2 || (c1.code - 'a'.code + 1) % 26 == c2.code - 'a'.code) { + found = true + break + } + } + if (!found) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2826_sorting_three_groups/readme.md b/src/main/kotlin/g2801_2900/s2826_sorting_three_groups/readme.md new file mode 100644 index 00000000..3fb6ac9a --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2826_sorting_three_groups/readme.md @@ -0,0 +1,94 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2826\. Sorting Three Groups + +Medium + +You are given a **0-indexed** integer array `nums` of length `n`. + +The numbers from `0` to `n - 1` are divided into three groups numbered from `1` to `3`, where number `i` belongs to group `nums[i]`. Notice that some groups may be **empty**. + +You are allowed to perform this operation any number of times: + +* Pick number `x` and change its group. More formally, change `nums[x]` to any number from `1` to `3`. + +A new array `res` is constructed using the following procedure: + +1. Sort the numbers in each group independently. +2. Append the elements of groups `1`, `2`, and `3` to `res` **in this order**. + +Array `nums` is called a **beautiful array** if the constructed array `res` is sorted in **non-decreasing** order. + +Return _the **minimum** number of operations to make_ `nums` _a **beautiful array**_. + +**Example 1:** + +**Input:** nums = [2,1,3,2,1] + +**Output:** 3 + +**Explanation:** It's optimal to perform three operations: +1. change nums[0] to 1. +2. change nums[2] to 1. +3. change nums[3] to 1. + +After performing the operations and sorting the numbers in each group, group 1 becomes equal to [0,1,2,3,4] and group 2 and group 3 become empty. Hence, res is equal to [0,1,2,3,4] which is sorted in non-decreasing order. + +It can be proven that there is no valid sequence of less than three operations. + +**Example 2:** + +**Input:** nums = [1,3,2,1,3,3] + +**Output:** 2 + +**Explanation:** It's optimal to perform two operations: +1. change nums[1] to 1. +2. change nums[2] to 1. + +After performing the operations and sorting the numbers in each group, group 1 becomes equal to [0,1,2,3], group 2 becomes empty, and group 3 becomes equal to [4,5]. Hence, res is equal to [0,1,2,3,4,5] which is sorted in non-decreasing order. + +It can be proven that there is no valid sequence of less than two operations. + +**Example 3:** + +**Input:** nums = [2,2,2,2,3,3] + +**Output:** 0 + +**Explanation:** It's optimal to not perform operations. + +After sorting the numbers in each group, group 1 becomes empty, group 2 becomes equal to [0,1,2,3] and group 3 becomes equal to [4,5]. Hence, res is equal to [0,1,2,3,4,5] which is sorted in non-decreasing order. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 3` + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun minimumOperations(nums: List): Int { + val n = nums.size + val arr = IntArray(3) + var max = 0 + for (num in nums) { + var locMax = 0 + val value = num + for (j in 0 until value) { + locMax = max(locMax, arr[j]) + } + locMax++ + arr[value - 1] = locMax + if (locMax > max) { + max = locMax + } + } + return n - max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/readme.md b/src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/readme.md new file mode 100644 index 00000000..11eee41e --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/readme.md @@ -0,0 +1,141 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2827\. Number of Beautiful Integers in the Range + +Hard + +You are given positive integers `low`, `high`, and `k`. + +A number is **beautiful** if it meets both of the following conditions: + +* The count of even digits in the number is equal to the count of odd digits. +* The number is divisible by `k`. + +Return _the number of beautiful integers in the range_ `[low, high]`. + +**Example 1:** + +**Input:** low = 10, high = 20, k = 3 + +**Output:** 2 + +**Explanation:** There are 2 beautiful integers in the given range: [12,18]. +- 12 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3. +- 18 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3. Additionally we can see that: +- 16 is not beautiful because it is not divisible by k = 3. +- 15 is not beautiful because it does not contain equal counts even and odd digits. It can be shown that there are only 2 beautiful integers in the given range. + +**Example 2:** + +**Input:** low = 1, high = 10, k = 1 + +**Output:** 1 + +**Explanation:** There is 1 beautiful integer in the given range: [10]. +- 10 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 1. It can be shown that there is only 1 beautiful integer in the given range. + +**Example 3:** + +**Input:** low = 5, high = 5, k = 2 + +**Output:** 0 + +**Explanation:** There are 0 beautiful integers in the given range. +- 5 is not beautiful because it is not divisible by k = 2 and it does not contain equal even and odd digits. + +**Constraints:** + +* 0 < low <= high <= 109 +* `0 < k <= 20` + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + private lateinit var dp: Array>>> + private var maxLength = 0 + + fun numberOfBeautifulIntegers(low: Int, high: Int, k: Int): Int { + val num1 = low.toString() + val num2 = high.toString() + maxLength = max(num1.length.toDouble(), num2.length.toDouble()).toInt() + dp = Array(4) { Array(maxLength) { Array(maxLength) { Array(maxLength) { IntArray(k) } } } } + for (a in dp) { + for (b in a) { + for (c in b) { + for (d in c) { + d.fill(-1) + } + } + } + } + return dp(num1, num2, 0, 3, 0, 0, 0, 0, k) + } + + private fun dp( + low: String, + high: String, + i: Int, + mode: Int, + odd: Int, + even: Int, + num: Int, + rem: Int, + k: Int + ): Int { + if (i == maxLength) { + return if (num % k == 0 && odd == even) 1 else 0 + } + if (dp[mode][i][odd][even][rem] != -1) { + return dp[mode][i][odd][even][rem] + } + var res = 0 + val lowLimit = mode % 2 == 1 + val highLimit = mode / 2 == 1 + var start = 0 + var end = 9 + if (lowLimit) { + start = digitAt(low, i) + } + if (highLimit) { + end = digitAt(high, i) + } + for (j in start..end) { + var newMode = 0 + if (j == start && lowLimit) { + newMode += 1 + } + if (j == end && highLimit) { + newMode += 2 + } + var newEven = even + if (num != 0 || j != 0) { + newEven += if (j % 2 == 0) 1 else 0 + } + val newOdd = odd + (if (j % 2 == 1) 1 else 0) + res += + dp( + low, + high, + i + 1, + newMode, + newOdd, + newEven, + num * 10 + j, + (num * 10 + j) % k, + k + ) + } + dp[mode][i][odd][even][rem] = res + return res + } + + private fun digitAt(num: String, i: Int): Int { + val index = num.length - maxLength + i + return if (index < 0) 0 else num[index].code - '0'.code + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2828_check_if_a_string_is_an_acronym_of_words/readme.md b/src/main/kotlin/g2801_2900/s2828_check_if_a_string_is_an_acronym_of_words/readme.md new file mode 100644 index 00000000..dc69b5ad --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2828_check_if_a_string_is_an_acronym_of_words/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2828\. Check if a String Is an Acronym of Words + +Easy + +Given an array of strings `words` and a string `s`, determine if `s` is an **acronym** of words. + +The string `s` is considered an acronym of `words` if it can be formed by concatenating the **first** character of each string in `words` **in order**. For example, `"ab"` can be formed from `["apple", "banana"]`, but it can't be formed from `["bear", "aardvark"]`. + +Return `true` _if_ `s` _is an acronym of_ `words`_, and_ `false` _otherwise._ + +**Example 1:** + +**Input:** words = ["alice","bob","charlie"], s = "abc" + +**Output:** true + +**Explanation:** The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym. + +**Example 2:** + +**Input:** words = ["an","apple"], s = "a" + +**Output:** false + +**Explanation:** The first character in the words "an" and "apple" are 'a' and 'a', respectively. The acronym formed by concatenating these characters is "aa". Hence, s = "a" is not the acronym. + +**Example 3:** + +**Input:** words = ["never","gonna","give","up","on","you"], s = "ngguoy" + +**Output:** true + +**Explanation:** By concatenating the first character of the words in the array, we get the string "ngguoy". Hence, s = "ngguoy" is the acronym. + +**Constraints:** + +* `1 <= words.length <= 100` +* `1 <= words[i].length <= 10` +* `1 <= s.length <= 100` +* `words[i]` and `s` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun isAcronym(words: List, s: String): Boolean { + if (s.length != words.size) { + return false + } + for (i in words.indices) { + if (words[i][0] != s[i]) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array/readme.md b/src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array/readme.md new file mode 100644 index 00000000..1265de8e --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2829\. Determine the Minimum Sum of a k-avoiding Array + +Medium + +You are given two integers, `n` and `k`. + +An array of **distinct** positive integers is called a **k-avoiding** array if there does not exist any pair of distinct elements that sum to `k`. + +Return _the **minimum** possible sum of a k-avoiding array of length_ `n`. + +**Example 1:** + +**Input:** n = 5, k = 4 + +**Output:** 18 + +**Explanation:** Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18. It can be proven that there is no k-avoiding array with a sum less than 18. + +**Example 2:** + +**Input:** n = 2, k = 6 + +**Output:** 3 + +**Explanation:** We can construct the array [1,2], which has a sum of 3. It can be proven that there is no k-avoiding array with a sum less than 3. + +**Constraints:** + +* `1 <= n, k <= 50` + +## Solution + +```kotlin +class Solution { + fun minimumSum(n: Int, k: Int): Int { + var k = k + val arr = IntArray(n) + val a = k / 2 + var sum = 0 + if (a > n) { + for (i in 0 until n) { + arr[i] = i + 1 + sum += arr[i] + } + } else { + for (i in 0 until a) { + arr[i] = i + 1 + sum += arr[i] + } + for (j in a until n) { + arr[j] = k++ + sum += arr[j] + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2830_maximize_the_profit_as_the_salesman/readme.md b/src/main/kotlin/g2801_2900/s2830_maximize_the_profit_as_the_salesman/readme.md new file mode 100644 index 00000000..2682507b --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2830_maximize_the_profit_as_the_salesman/readme.md @@ -0,0 +1,88 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2830\. Maximize the Profit as the Salesman + +Medium + +You are given an integer `n` representing the number of houses on a number line, numbered from `0` to `n - 1`. + +Additionally, you are given a 2D integer array `offers` where offers[i] = [starti, endi, goldi], indicating that ith buyer wants to buy all the houses from starti to endi for goldi amount of gold. + +As a salesman, your goal is to **maximize** your earnings by strategically selecting and selling houses to buyers. + +Return _the maximum amount of gold you can earn_. + +**Note** that different buyers can't buy the same house, and some houses may remain unsold. + +**Example 1:** + +**Input:** n = 5, offers = \[\[0,0,1],[0,2,2],[1,3,2]] + +**Output:** 3 + +**Explanation:** There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. + +We sell houses in the range [0,0] to 1st buyer for 1 gold and houses in the range [1,3] to 3rd buyer for 2 golds. + +It can be proven that 3 is the maximum amount of gold we can achieve. + +**Example 2:** + +**Input:** n = 5, offers = \[\[0,0,1],[0,2,10],[1,3,2]] + +**Output:** 10 + +**Explanation:** There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. + +We sell houses in the range [0,2] to 2nd buyer for 10 golds. + +It can be proven that 10 is the maximum amount of gold we can achieve. + +**Constraints:** + +* 1 <= n <= 105 +* 1 <= offers.length <= 105 +* `offers[i].length == 3` +* 0 <= starti <= endi <= n - 1 +* 1 <= goldi <= 103 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maximizeTheProfit(n: Int, offers: List>): Int { + val dp = IntArray(n) + val range = HashMap>>() + for (l in offers) { + if (range.containsKey(l[0])) { + range[l[0]]!!.add(l) + } else { + val r: MutableList> = ArrayList() + r.add(l) + range[l[0]] = r + } + } + var i = 0 + while (i < n) { + var temp: List> = ArrayList() + if (range.containsKey(i)) { + temp = range[i]!! + } + dp[i] = if ((i != 0)) max(dp[i], dp[i - 1]) else dp[i] + for (l in temp) { + dp[l[1]] = + if ((i != 0) + ) max(dp[l[1]], (dp[i - 1] + l[2])) else max( + dp[l[1]], + l[2] + ) + } + i++ + } + return dp[n - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2831_find_the_longest_equal_subarray/readme.md b/src/main/kotlin/g2801_2900/s2831_find_the_longest_equal_subarray/readme.md new file mode 100644 index 00000000..d76f59f3 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2831_find_the_longest_equal_subarray/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2831\. Find the Longest Equal Subarray + +Medium + +You are given a **0-indexed** integer array `nums` and an integer `k`. + +A subarray is called **equal** if all of its elements are equal. Note that the empty subarray is an **equal** subarray. + +Return _the length of the **longest** possible equal subarray after deleting **at most**_ `k` _elements from_ `nums`. + +A **subarray** is a contiguous, possibly empty sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [1,3,2,3,1,3], k = 3 + +**Output:** 3 + +**Explanation:** It's optimal to delete the elements at index 2 and index 4. + +After deleting them, nums becomes equal to [1, 3, 3, 3]. The longest equal subarray starts at i = 1 and ends at j = 3 with length equal to 3. + +It can be proven that no longer equal subarrays can be created. + +**Example 2:** + +**Input:** nums = [1,1,2,2,1,1], k = 2 + +**Output:** 4 + +**Explanation:** It's optimal to delete the elements at index 2 and index 3. + +After deleting them, nums becomes equal to [1, 1, 1, 1]. The array itself is an equal subarray, so the answer is 4. + +It can be proven that no longer equal subarrays can be created. + +**Constraints:** + +* 1 <= nums.length <= 105 +* `1 <= nums[i] <= nums.length` +* `0 <= k <= nums.length` + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun longestEqualSubarray(nums: List, k: Int): Int { + val count = IntArray(nums.size + 1) + var i = 0 + var maxCount = 0 + for (j in nums.indices) { + count[nums[j]]++ + maxCount = max(maxCount.toDouble(), count[nums[j]].toDouble()).toInt() + if ((j - i + 1) - maxCount > k) { + count[nums[i]]-- + i++ + } + } + return maxCount + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2833_furthest_point_from_origin/readme.md b/src/main/kotlin/g2801_2900/s2833_furthest_point_from_origin/readme.md new file mode 100644 index 00000000..b73927a9 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2833_furthest_point_from_origin/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2833\. Furthest Point From Origin + +Easy + +You are given a string `moves` of length `n` consisting only of characters `'L'`, `'R'`, and `'_'`. The string represents your movement on a number line starting from the origin `0`. + +In the ith move, you can choose one of the following directions: + +* move to the left if `moves[i] = 'L'` or `moves[i] = '_'` +* move to the right if `moves[i] = 'R'` or `moves[i] = '_'` + +Return _the **distance from the origin** of the **furthest** point you can get to after_ `n` _moves_. + +**Example 1:** + +**Input:** moves = "L\_RL\_\_R" + +**Output:** 3 + +**Explanation:** The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves "LLRLLLR". + +**Example 2:** + +**Input:** moves = "\_R\_\_LL\_" + +**Output:** 5 + +**Explanation:** The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves "LRLLLLL". + +**Example 3:** + +**Input:** moves = "\_\_\_\_\_\_\_" + +**Output:** 7 + +**Explanation:** The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves "RRRRRRR". + +**Constraints:** + +* `1 <= moves.length == n <= 50` +* `moves` consists only of characters `'L'`, `'R'` and `'_'`. + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun furthestDistanceFromOrigin(moves: String): Int { + var count = 0 + var res = 0 + for (i in moves.indices) { + if (moves[i] == 'L') { + res -= 1 + } else if (moves[i] == 'R') { + res += 1 + } else { + count++ + } + } + return abs(res) + count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2834_find_the_minimum_possible_sum_of_a_beautiful_array/readme.md b/src/main/kotlin/g2801_2900/s2834_find_the_minimum_possible_sum_of_a_beautiful_array/readme.md new file mode 100644 index 00000000..888b9c6a --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2834_find_the_minimum_possible_sum_of_a_beautiful_array/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2834\. Find the Minimum Possible Sum of a Beautiful Array + +Medium + +You are given positive integers `n` and `target`. + +An array `nums` is **beautiful** if it meets the following conditions: + +* `nums.length == n`. +* `nums` consists of pairwise **distinct** **positive** integers. +* There doesn't exist two **distinct** indices, `i` and `j`, in the range `[0, n - 1]`, such that `nums[i] + nums[j] == target`. + +Return _the **minimum** possible sum that a beautiful array could have modulo_ 109 + 7. + +**Example 1:** + +**Input:** n = 2, target = 3 + +**Output:** 4 + +**Explanation:** We can see that nums = [1,3] is beautiful. +- The array nums has length n = 2. +- The array nums consists of pairwise distinct positive integers. +- There doesn't exist two distinct indices, i and j, with nums[i] + nums[j] == 3. + +It can be proven that 4 is the minimum possible sum that a beautiful array could have. + +**Example 2:** + +**Input:** n = 3, target = 3 + +**Output:** 8 + +**Explanation:** We can see that nums = [1,3,4] is beautiful. +- The array nums has length n = 3. +- The array nums consists of pairwise distinct positive integers. +- There doesn't exist two distinct indices, i and j, with nums[i] + nums[j] == 3. + +It can be proven that 8 is the minimum possible sum that a beautiful array could have. + +**Example 3:** + +**Input:** n = 1, target = 1 + +**Output:** 1 + +**Explanation:** We can see, that nums = [1] is beautiful. + +**Constraints:** + +* 1 <= n <= 109 +* 1 <= target <= 109 + +## Solution + +```kotlin +class Solution { + fun minimumPossibleSum(n: Int, target: Int): Int { + val mod = 1e9.toLong() + 7 + if (target > (n + n - 1)) { + return (n.toLong() * (n + 1) % mod / 2).toInt() + } + val toChange = n - (target / 2).toLong() + val sum = ((n * (n.toLong() + 1)) / 2) % mod + val remain = target.toLong() - ((target / 2) + 1) + return ((sum + (toChange * remain) % mod) % mod).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum/readme.md b/src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum/readme.md new file mode 100644 index 00000000..eaea4ed5 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum/readme.md @@ -0,0 +1,95 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2835\. Minimum Operations to Form Subsequence With Target Sum + +Hard + +You are given a **0-indexed** array `nums` consisting of **non-negative** powers of `2`, and an integer `target`. + +In one operation, you must apply the following changes to the array: + +* Choose any element of the array `nums[i]` such that `nums[i] > 1`. +* Remove `nums[i]` from the array. +* Add **two** occurrences of `nums[i] / 2` to the **end** of `nums`. + +Return the _**minimum number of operations** you need to perform so that_ `nums` _contains a **subsequence** whose elements sum to_ `target`. If it is impossible to obtain such a subsequence, return `-1`. + +A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. + +**Example 1:** + +**Input:** nums = [1,2,8], target = 7 + +**Output:** 1 + +**Explanation:** In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4]. + +At this stage, nums contains the subsequence [1,2,4] which sums up to 7. + +It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7. + +**Example 2:** + +**Input:** nums = [1,32,1,2], target = 12 + +**Output:** 2 + +**Explanation:** In the first operation, we choose element nums[1]. The array becomes equal to nums = [1,1,2,16,16]. + +In the second operation, we choose element nums[3]. The array becomes equal to nums = [1,1,2,16,8,8] + +At this stage, nums contains the subsequence [1,1,2,8] which sums up to 12. + +It can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12. + +**Example 3:** + +**Input:** nums = [1,32,1], target = 35 + +**Output:** -1 + +**Explanation:** It can be shown that no sequence of operations results in a subsequence that sums up to 35. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 1 <= nums[i] <= 230 +* `nums` consists only of non-negative powers of two. +* 1 <= target < 231 + +## Solution + +```kotlin +import java.util.PriorityQueue + +@Suppress("NAME_SHADOWING") +class Solution { + fun minOperations(nums: List, target: Int): Int { + var target = target + val pq = PriorityQueue { a: Int, b: Int -> b - a } + var sum: Long = 0 + var count: Long = 0 + for (x in nums) { + pq.offer(x) + sum += x.toLong() + } + if (sum < target) { + return -1 + } + while (!pq.isEmpty()) { + val `val` = pq.poll() + sum -= `val`.toLong() + if (`val` <= target) { + target -= `val` + } else if (sum < target) { + count++ + pq.offer(`val` / 2) + pq.offer(`val` / 2) + sum += `val`.toLong() + } + } + return count.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2836_maximize_value_of_function_in_a_ball_passing_game/readme.md b/src/main/kotlin/g2801_2900/s2836_maximize_value_of_function_in_a_ball_passing_game/readme.md new file mode 100644 index 00000000..cd490370 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2836_maximize_value_of_function_in_a_ball_passing_game/readme.md @@ -0,0 +1,108 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2836\. Maximize Value of Function in a Ball Passing Game + +Hard + +You are given a **0-indexed** integer array `receiver` of length `n` and an integer `k`. + +There are `n` players having a **unique id** in the range `[0, n - 1]` who will play a ball passing game, and `receiver[i]` is the id of the player who receives passes from the player with id `i`. Players can pass to themselves, **i.e.** `receiver[i]` may be equal to `i`. + +You must choose one of the `n` players as the starting player for the game, and the ball will be passed **exactly** `k` times starting from the chosen player. + +For a chosen starting player having id `x`, we define a function `f(x)` that denotes the **sum** of `x` and the **ids** of all players who receive the ball during the `k` passes, **including repetitions**. In other words, f(x) = x + receiver[x] + receiver[receiver[x]] + ... + receiver(k)[x]. + +Your task is to choose a starting player having id `x` that **maximizes** the value of `f(x)`. + +Return _an integer denoting the **maximum** value of the function._ + +**Note:** `receiver` may contain duplicates. + +**Example 1:** + +\| Pass Number \| Sender ID \| Receiver ID \| x + Receiver IDs +\|-------------\|-----------\|-------------\|----------------- +\| \| \| \| 2 +\| 1 \| 2 \| 1 \| 3 +\| 2 \| 1 \| 0 \| 3 +\| 3 \| 0 \| 2 \| 5 +\| 4 \| 2 \| 1 \| 6 + +**Input:** receiver = [2,0,1], k = 4 + +**Output:** 6 + +**Explanation:** The table above shows a simulation of the game starting with the player having id x = 2. From the table, f(2) is equal to 6. It can be shown that 6 is the maximum achievable value of the function. Hence, the output is 6. + +**Example 2:** + +\| Pass Number \| Sender ID \| Receiver ID \| x + Receiver IDs +\|-------------\|-----------\|-------------\|----------------- +\| \| \| \| 4 +\| 1 \| 4 \| 3 \| 7 +\| 2 \| 3 \| 2 \| 9 +\| 3 \| 2 \| 1 \| 10 + +**Input:** receiver = [1,1,1,2,3], k = 3 + +**Output:** 10 + +**Explanation:** The table above shows a simulation of the game starting with the player having id x = 4. From the table, f(4) is equal to 10. It can be shown that 10 is the maximum achievable value of the function. Hence, the output is 10. + +**Constraints:** + +* 1 <= receiver.length == n <= 105 +* `0 <= receiver[i] <= n - 1` +* 1 <= k <= 1010 + +## Solution + +```kotlin +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.max + +class Solution { + fun getMaxFunctionValue(receiver: List, k: Long): Long { + val upper = floor(ln(k.toDouble()) / ln(2.0)).toInt() + val n = receiver.size + val next = Array(n) { IntArray(upper + 1) } + val res = Array(n) { LongArray(upper + 1) } + val kBit = IntArray(upper + 1) + var currK = k + for (x in 0 until n) { + next[x][0] = receiver[x] + res[x][0] = receiver[x].toLong() + } + for (i in 0..upper) { + kBit[i] = (currK and 1L).toInt() + currK = currK shr 1 + } + for (i in 1..upper) { + for (x in 0 until n) { + val nxt = next[x][i - 1] + next[x][i] = next[nxt][i - 1] + res[x][i] = res[x][i - 1] + res[nxt][i - 1] + } + } + var ans: Long = 0 + for (x in 0 until n) { + var sum = x.toLong() + var i = 0 + var curr = x + while (i <= upper) { + if (kBit[i] == 0) { + i++ + continue + } + sum += res[curr][i] + curr = next[curr][i] + i++ + } + ans = max(ans, sum) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2839_check_if_strings_can_be_made_equal_with_operations_i/readme.md b/src/main/kotlin/g2801_2900/s2839_check_if_strings_can_be_made_equal_with_operations_i/readme.md new file mode 100644 index 00000000..5d88cfb0 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2839_check_if_strings_can_be_made_equal_with_operations_i/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2839\. Check if Strings Can be Made Equal With Operations I + +Easy + +You are given two strings `s1` and `s2`, both of length `4`, consisting of **lowercase** English letters. + +You can apply the following operation on any of the two strings **any** number of times: + +* Choose any two indices `i` and `j` such that `j - i = 2`, then **swap** the two characters at those indices in the string. + +Return `true` _if you can make the strings_ `s1` _and_ `s2` _equal, and_ `false` _otherwise_. + +**Example 1:** + +**Input:** s1 = "abcd", s2 = "cdab" + +**Output:** true + +**Explanation:** We can do the following operations on s1: +- Choose the indices i = 0, j = 2. The resulting string is s1 = "cbad". +- Choose the indices i = 1, j = 3. The resulting string is s1 = "cdab" = s2. + +**Example 2:** + +**Input:** s1 = "abcd", s2 = "dacb" + +**Output:** false + +**Explanation:** It is not possible to make the two strings equal. + +**Constraints:** + +* `s1.length == s2.length == 4` +* `s1` and `s2` consist only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun canBeEqual(s1: String, s2: String): Boolean { + return isOk(s1, s2, 0) && isOk(s1, s2, 1) + } + + private fun isOk(s1: String, s2: String, i: Int): Boolean { + val a = s1[i] + val b = s1[i + 2] + val c = s2[i] + val d = s2[i + 2] + if (a == c && b == d) { + return true + } + return a == d && b == c + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2840_check_if_strings_can_be_made_equal_with_operations_ii/readme.md b/src/main/kotlin/g2801_2900/s2840_check_if_strings_can_be_made_equal_with_operations_ii/readme.md new file mode 100644 index 00000000..bc6b7115 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2840_check_if_strings_can_be_made_equal_with_operations_ii/readme.md @@ -0,0 +1,66 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2840\. Check if Strings Can be Made Equal With Operations II + +Medium + +You are given two strings `s1` and `s2`, both of length `n`, consisting of **lowercase** English letters. + +You can apply the following operation on **any** of the two strings **any** number of times: + +* Choose any two indices `i` and `j` such that `i < j` and the difference `j - i` is **even**, then **swap** the two characters at those indices in the string. + +Return `true` _if you can make the strings_ `s1` _and_ `s2` _equal, and_`false` _otherwise_. + +**Example 1:** + +**Input:** s1 = "abcdba", s2 = "cabdab" + +**Output:** true + +**Explanation:** We can apply the following operations on s1: +- Choose the indices i = 0, j = 2. The resulting string is s1 = "cbadba". +- Choose the indices i = 2, j = 4. The resulting string is s1 = "cbbdaa". +- Choose the indices i = 1, j = 5. The resulting string is s1 = "cabdab" = s2. + +**Example 2:** + +**Input:** s1 = "abe", s2 = "bea" + +**Output:** false + +**Explanation:** It is not possible to make the two strings equal. + +**Constraints:** + +* `n == s1.length == s2.length` +* 1 <= n <= 105 +* `s1` and `s2` consist only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun checkStrings(s1: String, s2: String): Boolean { + return check(0, s1, s2) && check(1, s1, s2) + } + + fun check(start: Int, s1: String, s2: String): Boolean { + val step = 2 + val buf = IntArray(26) + var i = start + while (i < s1.length) { + buf[s1[i].code - 'a'.code]++ + buf[s2[i].code - 'a'.code]-- + i += step + } + for (j in buf) { + if (j != 0) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2841_maximum_sum_of_almost_unique_subarray/readme.md b/src/main/kotlin/g2801_2900/s2841_maximum_sum_of_almost_unique_subarray/readme.md new file mode 100644 index 00000000..88e24248 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2841_maximum_sum_of_almost_unique_subarray/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2841\. Maximum Sum of Almost Unique Subarray + +Medium + +You are given an integer array `nums` and two positive integers `m` and `k`. + +Return _the **maximum sum** out of all **almost unique** subarrays of length_ `k` _of_ `nums`. If no such subarray exists, return `0`. + +A subarray of `nums` is **almost unique** if it contains at least `m` distinct elements. + +A subarray is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [2,6,7,3,1,7], m = 3, k = 4 + +**Output:** 18 + +**Explanation:** There are 3 almost unique subarrays of size `k = 4`. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18. + +**Example 2:** + +**Input:** nums = [5,9,9,2,4,5,4], m = 1, k = 3 + +**Output:** 23 + +**Explanation:** There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23. + +**Example 3:** + +**Input:** nums = [1,2,1,2,1,2,1], m = 3, k = 3 + +**Output:** 0 + +**Explanation:** There are no subarrays of size `k = 3` that contain at least `m = 3` distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0. + +**Constraints:** + +* 1 <= nums.length <= 2 * 104 +* `1 <= m <= k <= nums.length` +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maxSum(nums: List, m: Int, k: Int): Long { + val hash = HashMap() + var count = 0 + var ans: Long = 0 + var left = 0 + var cur: Long = 0 + for (i in nums.indices) { + cur += nums[i].toLong() + if (hash.containsKey(nums[i])) { + hash[nums[i]] = hash.getValue(nums[i]) + 1 + } else { + hash[nums[i]] = 1 + count++ + } + if (i - left + 1 == k) { + if (count >= m) { + ans = max(ans.toDouble(), cur.toDouble()).toLong() + } + if (hash[nums[left]]!! > 1) { + hash[nums[left]] = hash.getValue(nums[left]) - 1 + } else { + count-- + hash.remove(nums[left]) + } + cur -= nums[left].toLong() + left++ + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty/readme.md b/src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty/readme.md new file mode 100644 index 00000000..1df41922 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty/readme.md @@ -0,0 +1,109 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2842\. Count K-Subsequences of a String With Maximum Beauty + +Hard + +You are given a string `s` and an integer `k`. + +A **k-subsequence** is a **subsequence** of `s`, having length `k`, and all its characters are **unique**, **i.e**., every character occurs once. + +Let `f(c)` denote the number of times the character `c` occurs in `s`. + +The **beauty** of a **k-subsequence** is the **sum** of `f(c)` for every character `c` in the k-subsequence. + +For example, consider `s = "abbbdd"` and `k = 2`: + +* `f('a') = 1`, `f('b') = 3`, `f('d') = 2` +* Some k-subsequences of `s` are: + * "**ab**bbdd" -> `"ab"` having a beauty of `f('a') + f('b') = 4` + * "**a**bbb**d**d" -> `"ad"` having a beauty of `f('a') + f('d') = 3` + * "a**b**bb**d**d" -> `"bd"` having a beauty of `f('b') + f('d') = 5` + +Return _an integer denoting the number of k-subsequences_ _whose **beauty** is the **maximum** among all **k-subsequences**_. Since the answer may be too large, return it modulo 109 + 7. + +A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters. + +**Notes** + +* `f(c)` is the number of times a character `c` occurs in `s`, not a k-subsequence. +* Two k-subsequences are considered different if one is formed by an index that is not present in the other. So, two k-subsequences may form the same string. + +**Example 1:** + +**Input:** s = "bcca", k = 2 + +**Output:** 4 + +**Explanation:** From s we have f('a') = 1, f('b') = 1, and f('c') = 2. The k-subsequences of s are: + +**bc**ca having a beauty of f('b') + f('c') = 3 + +**b**c**c**a having a beauty of f('b') + f('c') = 3 + +**b**cc**a** having a beauty of f('b') + f('a') = 2 + +b**c**c**a** having a beauty of f('c') + f('a') = 3 + +bc**ca** having a beauty of f('c') + f('a') = 3 + +There are 4 k-subsequences that have the maximum beauty, 3. Hence, the answer is 4. + +**Example 2:** + +**Input:** s = "abbcd", k = 4 + +**Output:** 2 + +**Explanation:** From s we have f('a') = 1, f('b') = 2, f('c') = 1, and f('d') = 1. The k-subsequences of s are: + +**ab**b**cd** having a beauty of f('a') + f('b') + f('c') + f('d') = 5 + +**a**b**bcd** having a beauty of f('a') + f('b') + f('c') + f('d') = 5 + +There are 2 k-subsequences that have the maximum beauty, 5. Hence, the answer is 2. + +**Constraints:** + +* 1 <= s.length <= 2 * 105 +* `1 <= k <= s.length` +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun countKSubsequencesWithMaxBeauty(s: String, k: Int): Int { + var k = k + val n = s.length + val count = IntArray(26) + for (i in 0 until n) { + count[s[i].code - 'a'.code]++ + } + count.sort() + if (k > 26 || count[26 - k] == 0) { + return 0 + } + var res: Long = 1 + var comb: Long = 1 + val mod = 1e9.toLong() + 7 + val bar = count[26 - k].toLong() + var pend: Long = 0 + for (freq in count) { + if (freq > bar) { + k-- + res = res * freq % mod + } + if (freq.toLong() == bar) { + pend++ + } + } + for (i in 0 until k) { + comb = comb * (pend - i) / (i + 1) + res = res * bar % mod + } + return (res * comb % mod).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2843_count_symmetric_integers/readme.md b/src/main/kotlin/g2801_2900/s2843_count_symmetric_integers/readme.md new file mode 100644 index 00000000..2fa2fae2 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2843_count_symmetric_integers/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2843\. Count Symmetric Integers + +Easy + +You are given two positive integers `low` and `high`. + +An integer `x` consisting of `2 * n` digits is **symmetric** if the sum of the first `n` digits of `x` is equal to the sum of the last `n` digits of `x`. Numbers with an odd number of digits are never symmetric. + +Return _the **number of symmetric** integers in the range_ `[low, high]`. + +**Example 1:** + +**Input:** low = 1, high = 100 + +**Output:** 9 + +**Explanation:** There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99. + +**Example 2:** + +**Input:** low = 1200, high = 1230 + +**Output:** 4 + +**Explanation:** There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230. + +**Constraints:** + +* 1 <= low <= high <= 104 + +## Solution + +```kotlin +class Solution { + fun countSymmetricIntegers(low: Int, high: Int): Int { + var count = 0 + for (i in low..high) { + if (isSymmetric(i)) { + count++ + } + } + return count + } + + private fun isSymmetric(num: Int): Boolean { + val str = num.toString() + val n = str.length + if (n % 2 != 0) { + return false + } + var leftSum = 0 + var rightSum = 0 + var i = 0 + var j = n - 1 + while (i < j) { + leftSum += str[i].code - '0'.code + rightSum += str[j].code - '0'.code + i++ + j-- + } + return leftSum == rightSum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2844_minimum_operations_to_make_a_special_number/readme.md b/src/main/kotlin/g2801_2900/s2844_minimum_operations_to_make_a_special_number/readme.md new file mode 100644 index 00000000..8474482d --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2844_minimum_operations_to_make_a_special_number/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2844\. Minimum Operations to Make a Special Number + +Medium + +You are given a **0-indexed** string `num` representing a non-negative integer. + +In one operation, you can pick any digit of `num` and delete it. Note that if you delete all the digits of `num`, `num` becomes `0`. + +Return _the **minimum number of operations** required to make_ `num` _special_. + +An integer `x` is considered **special** if it is divisible by `25`. + +**Example 1:** + +**Input:** num = "2245047" + +**Output:** 2 + +**Explanation:** Delete digits num[5] and num[6]. The resulting number is "22450" which is special since it is divisible by 25. It can be shown that 2 is the minimum number of operations required to get a special number. + +**Example 2:** + +**Input:** num = "2908305" + +**Output:** 3 + +**Explanation:** Delete digits num[3], num[4], and num[6]. The resulting number is "2900" which is special since it is divisible by 25. It can be shown that 3 is the minimum number of operations required to get a special number. + +**Example 3:** + +**Input:** num = "10" + +**Output:** 1 + +**Explanation:** Delete digit num[0]. The resulting number is "0" which is special since it is divisible by 25. It can be shown that 1 is the minimum number of operations required to get a special number. + +**Constraints:** + +* `1 <= num.length <= 100` +* `num` only consists of digits `'0'` through `'9'`. +* `num` does not contain any leading zeros. + +## Solution + +```kotlin +class Solution { + fun minimumOperations(num: String): Int { + val number = num.toCharArray() + val n = number.size + var zero = 0 + var five = 0 + for (i in n - 1 downTo 0) { + if (number[i] == '0') { + if (zero == 1) { + return n - i - 2 + } else { + zero++ + } + } else if (number[i] == '5') { + if (zero == 1) { + return n - i - 2 + } + if (five == 0) { + five++ + } + } else if ((number[i] == '2' || number[i] == '7') && five == 1) { + return n - i - 2 + } + } + if (zero == 1) { + return n - 1 + } + return n + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2845_count_of_interesting_subarrays/readme.md b/src/main/kotlin/g2801_2900/s2845_count_of_interesting_subarrays/readme.md new file mode 100644 index 00000000..f1259d7d --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2845_count_of_interesting_subarrays/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2845\. Count of Interesting Subarrays + +Medium + +You are given a **0-indexed** integer array `nums`, an integer `modulo`, and an integer `k`. + +Your task is to find the count of subarrays that are **interesting**. + +A **subarray** `nums[l..r]` is **interesting** if the following condition holds: + +* Let `cnt` be the number of indices `i` in the range `[l, r]` such that `nums[i] % modulo == k`. Then, `cnt % modulo == k`. + +Return _an integer denoting the count of interesting subarrays._ + +**Note:** A subarray is _a contiguous non-empty sequence of elements within an array_. + +**Example 1:** + +**Input:** nums = [3,2,4], modulo = 2, k = 1 + +**Output:** 3 + +**Explanation:** In this example the interesting subarrays are: The subarray nums[0..0] which is [3]. +- There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. +- Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..1] which is [3,2]. +- There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k. +- Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..2] which is [3,2,4]. +- There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. +- Hence, cnt = 1 and cnt % modulo == k. + +It can be shown that there are no other interesting subarrays. So, the answer is 3. + +**Example 2:** + +**Input:** nums = [3,1,9,6], modulo = 3, k = 0 + +**Output:** 2 + +**Explanation:** In this example the interesting subarrays are: The subarray nums[0..3] which is [3,1,9,6]. +- There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. +- Hence, cnt = 3 and cnt % modulo == k. The subarray nums[1..1] which is [1]. +- There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. +- Hence, cnt = 0 and cnt % modulo == k. + +It can be shown that there are no other interesting subarrays. So, the answer is 2. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* 1 <= modulo <= 109 +* `0 <= k < modulo` + +## Solution + +```kotlin +class Solution { + fun countInterestingSubarrays(nums: List, modulo: Int, k: Int): Long { + var prefixCnt = 0 + val freq: MutableMap = HashMap() + freq[0] = 1 + var interestingSubarrays: Long = 0 + for (num in nums) { + if (num % modulo == k) { + prefixCnt++ + } + val expectedPrefix = (prefixCnt - k + modulo) % modulo + interestingSubarrays += freq.getOrDefault(expectedPrefix, 0).toLong() + freq[prefixCnt % modulo] = freq.getOrDefault(prefixCnt % modulo, 0) + 1 + } + return interestingSubarrays + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/readme.md b/src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/readme.md new file mode 100644 index 00000000..3654d1a3 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/readme.md @@ -0,0 +1,204 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2846\. Minimum Edge Weight Equilibrium Queries in a Tree + +Hard + +There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where edges[i] = [ui, vi, wi] indicates that there is an edge between nodes ui and vi with weight wi in the tree. + +You are also given a 2D integer array `queries` of length `m`, where queries[i] = [ai, bi]. For each query, find the **minimum number of operations** required to make the weight of every edge on the path from ai to bi equal. In one operation, you can choose any edge of the tree and change its weight to any value. + +**Note** that: + +* Queries are **independent** of each other, meaning that the tree returns to its **initial state** on each new query. +* The path from ai to bi is a sequence of **distinct** nodes starting with node ai and ending with node bi such that every two adjacent nodes in the sequence share an edge in the tree. + +Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ ith _query._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/08/11/graph-6-1.png) + +**Input:** n = 7, edges = \[\[0,1,1],[1,2,1],[2,3,1],[3,4,2],[4,5,2],[5,6,2]], queries = \[\[0,3],[3,6],[2,6],[0,6]] + +**Output:** [0,0,1,3] + +**Explanation:** In the first query, all the edges in the path from 0 to 3 have a weight of 1. Hence, the answer is 0. + +In the second query, all the edges in the path from 3 to 6 have a weight of 2. Hence, the answer is 0. In the third query, we change the weight of edge [2,3] to 2. After this operation, all the edges in the path from 2 to 6 have a weight of 2. Hence, the answer is 1. + +In the fourth query, we change the weights of edges [0,1], [1,2] and [2,3] to 2. After these operations, all the edges in the path from 0 to 6 have a weight of 2. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from ai to bi. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/08/11/graph-9-1.png) + +**Input:** n = 8, edges = \[\[1,2,6],[1,3,4],[2,4,6],[2,5,3],[3,6,6],[3,0,8],[7,0,2]], queries = \[\[4,6],[0,4],[6,5],[7,4]] + +**Output:** [1,2,2,3] + +**Explanation:** In the first query, we change the weight of edge [1,3] to 6. After this operation, all the edges in the path from 4 to 6 have a weight of 6. Hence, the answer is 1. + +In the second query, we change the weight of edges [0,3] and [3,1] to 6. After these operations, all the edges in the path from 0 to 4 have a weight of 6. Hence, the answer is 2. + +In the third query, we change the weight of edges [1,3] and [5,2] to 6. After these operations, all the edges in the path from 6 to 5 have a weight of 6. Hence, the answer is 2. + +In the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6. After these operations, all the edges in the path from 7 to 4 have a weight of 6. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from ai to bi. + +**Constraints:** + +* 1 <= n <= 104 +* `edges.length == n - 1` +* `edges[i].length == 3` +* 0 <= ui, vi < n +* 1 <= wi <= 26 +* The input is generated such that `edges` represents a valid tree. +* 1 <= queries.length == m <= 2 * 104 +* `queries[i].length == 2` +* 0 <= ai, bi < n + +## Solution + +```kotlin +import kotlin.math.ln +import kotlin.math.max + +class Solution { + private class Node(var v: Int, var w: Int) + + fun minOperationsQueries(n: Int, edges: Array, queries: Array): IntArray { + val graph = createGraph(edges, n) + val queryCount = queries.size + val res = IntArray(queryCount) + val parent = IntArray(n) + val level = IntArray(n) + val weightFreq = Array(n) { IntArray(27) } + val freq = IntArray(27) + val height = (ln(n.toDouble()) / ln(2.0)).toInt() + 1 + val up = Array(n) { IntArray(height) } + for (arr in up) { + arr.fill(-1) + } + dfs(graph, 0, 0, -1, parent, level, weightFreq, freq) + for (i in 0 until n) { + up[i][0] = parent[i] + } + for (i in 1 until height) { + for (j in 0 until n) { + if (up[j][i - 1] == -1) { + up[j][i] = -1 + continue + } + up[j][i] = up[up[j][i - 1]][i - 1] + } + } + for (i in 0 until queryCount) { + val src = queries[i][0] + val dest = queries[i][1] + val lcaNode = lca(src, dest, up, height, level) + res[i] = processResult(weightFreq[src], weightFreq[dest], weightFreq[lcaNode]) + } + return res + } + + private fun lca(src: Int, dest: Int, up: Array, height: Int, level: IntArray): Int { + var curr1 = src + var curr2 = dest + val minlevel: Int + if (level[curr1] > level[curr2]) { + minlevel = level[curr2] + curr1 = getKthAncestor(curr1, level[curr1] - level[curr2], up, height) + } else if (level[curr1] <= level[curr2]) { + minlevel = level[curr1] + curr2 = getKthAncestor(curr2, level[curr2] - level[curr1], up, height) + } else { + minlevel = level[curr1] + } + if (curr1 == curr2) { + return curr1 + } + var l = 0 + var h = level[curr2] + while (l <= h) { + val mid = l + (h - l) / 2 + val p1 = getKthAncestor(curr1, minlevel - mid, up, height) + val p2 = getKthAncestor(curr2, minlevel - mid, up, height) + if (p1 == p2) { + l = mid + 1 + } else { + h = mid - 1 + } + } + return getKthAncestor(curr1, minlevel - l + 1, up, height) + } + + private fun getKthAncestor(node: Int, k: Int, up: Array, height: Int): Int { + var curr = node + var i = 0 + while (i < height && k shr i != 0) { + if (((1 shl i) and k) != 0) { + if (curr == -1) { + return -1 + } + curr = up[curr][i] + } + i++ + } + return curr + } + + private fun processResult(freqSrc: IntArray, freqDest: IntArray, freqLCA: IntArray): Int { + val freqPath = IntArray(27) + for (i in 1..26) { + freqPath[i] = freqSrc[i] + freqDest[i] - 2 * freqLCA[i] + } + var max = 0 + var pathlen = 0 + for (i in 1..26) { + max = max(max.toDouble(), freqPath[i].toDouble()).toInt() + pathlen += freqPath[i] + } + return pathlen - max + } + + private fun dfs( + graph: List>, + src: Int, + currlevel: Int, + p: Int, + parent: IntArray, + level: IntArray, + weightFreq: Array, + freq: IntArray + ) { + parent[src] = p + level[src] = currlevel + System.arraycopy(freq, 0, weightFreq[src], 0, freq.size) + for (node in graph[src]) { + val v = node.v + val w = node.w + if (v != p) { + freq[w]++ + dfs(graph, v, currlevel + 1, src, parent, level, weightFreq, freq) + freq[w]-- + } + } + } + + private fun createGraph(edges: Array, n: Int): List> { + val graph: MutableList> = ArrayList() + for (i in 0 until n) { + graph.add(ArrayList()) + } + for (edge in edges) { + val u = edge[0] + val v = edge[1] + val w = edge[2] + graph[u].add(Node(v, w)) + graph[v].add(Node(u, w)) + } + return graph + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2848_points_that_intersect_with_cars/readme.md b/src/main/kotlin/g2801_2900/s2848_points_that_intersect_with_cars/readme.md new file mode 100644 index 00000000..55518fe6 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2848_points_that_intersect_with_cars/readme.md @@ -0,0 +1,66 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2848\. Points That Intersect With Cars + +Easy + +You are given a **0-indexed** 2D integer array `nums` representing the coordinates of the cars parking on a number line. For any index `i`, nums[i] = [starti, endi] where starti is the starting point of the ith car and endi is the ending point of the ith car. + +Return _the number of integer points on the line that are covered with **any part** of a car._ + +**Example 1:** + +**Input:** nums = \[\[3,6],[1,5],[4,7]] + +**Output:** 7 + +**Explanation:** All the points from 1 to 7 intersect at least one car, therefore the answer would be 7. + +**Example 2:** + +**Input:** nums = \[\[1,3],[5,8]] + +**Output:** 7 + +**Explanation:** Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `nums[i].length == 2` +* 1 <= starti <= endi <= 100 + +## Solution + +```kotlin +class Solution { + fun numberOfPoints(nums: List>): Int { + var min = 101 + var max = 0 + val count = IntArray(102) + for (list in nums) { + val num1 = list[0] + val num2 = list[1] + if (num1 < min) { + min = num1 + } + if (num2 > max) { + max = num2 + } + count[num1]-- + count[num2 + 1]++ + } + var result = 0 + var balance = 0 + while (min <= max) { + balance += count[min] + if (balance < 0) { + result++ + } + min++ + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2849_determine_if_a_cell_is_reachable_at_a_given_time/readme.md b/src/main/kotlin/g2801_2900/s2849_determine_if_a_cell_is_reachable_at_a_given_time/readme.md new file mode 100644 index 00000000..85046ce5 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2849_determine_if_a_cell_is_reachable_at_a_given_time/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2849\. Determine if a Cell Is Reachable at a Given Time + +Medium + +You are given four integers `sx`, `sy`, `fx`, `fy`, and a **non-negative** integer `t`. + +In an infinite 2D grid, you start at the cell `(sx, sy)`. Each second, you **must** move to any of its adjacent cells. + +Return `true` _if you can reach cell_ `(fx, fy)` _after **exactly**_ `t` **_seconds_**, _or_ `false` _otherwise_. + +A cell's **adjacent cells** are the 8 cells around it that share at least one corner with it. You can visit the same cell several times. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/08/05/example2.svg) + +**Input:** sx = 2, sy = 4, fx = 7, fy = 7, t = 6 + +**Output:** true + +**Explanation:** Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/08/05/example1.svg) + +**Input:** sx = 3, sy = 1, fx = 7, fy = 3, t = 3 + +**Output:** false + +**Explanation:** Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. + +**Constraints:** + +* 1 <= sx, sy, fx, fy <= 109 +* 0 <= t <= 109 + +## Solution + +```kotlin +import kotlin.math.abs +import kotlin.math.max + +class Solution { + fun isReachableAtTime(sx: Int, sy: Int, fx: Int, fy: Int, t: Int): Boolean { + if (sx == fx && sy == fy) { + return t != 1 + } + val width = abs((sx - fx)) + 1 + val height = abs((sy - fy)) + 1 + return max(width, height) - 1 <= t + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2850_minimum_moves_to_spread_stones_over_grid/readme.md b/src/main/kotlin/g2801_2900/s2850_minimum_moves_to_spread_stones_over_grid/readme.md new file mode 100644 index 00000000..1d052c63 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2850_minimum_moves_to_spread_stones_over_grid/readme.md @@ -0,0 +1,100 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2850\. Minimum Moves to Spread Stones Over Grid + +Medium + +You are given a **0-indexed** 2D integer matrix `grid` of size `3 * 3`, representing the number of stones in each cell. The grid contains exactly `9` stones, and there can be **multiple** stones in a single cell. + +In one move, you can move a single stone from its current cell to any other cell if the two cells share a side. + +Return _the **minimum number of moves** required to place one stone in each cell_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/08/23/example1-3.svg) + +**Input:** grid = \[\[1,1,0],[1,1,1],[1,2,1]] + +**Output:** 3 + +**Explanation:** One possible sequence of moves to place one stone in each cell is: + +1- Move one stone from cell (2,1) to cell (2,2). + +2- Move one stone from cell (2,2) to cell (1,2). + +3- Move one stone from cell (1,2) to cell (0,2). + +In total, it takes 3 moves to place one stone in each cell of the grid. + +It can be shown that 3 is the minimum number of moves required to place one stone in each cell. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/08/23/example2-2.svg) + +**Input:** grid = \[\[1,3,0],[1,0,0],[1,0,3]] + +**Output:** 4 + +**Explanation:** One possible sequence of moves to place one stone in each cell is: + +1- Move one stone from cell (0,1) to cell (0,2). + +2- Move one stone from cell (0,1) to cell (1,1). + +3- Move one stone from cell (2,2) to cell (1,2). + +4- Move one stone from cell (2,2) to cell (2,1). + +In total, it takes 4 moves to place one stone in each cell of the grid. + +It can be shown that 4 is the minimum number of moves required to place one stone in each cell. + +**Constraints:** + +* `grid.length == grid[i].length == 3` +* `0 <= grid[i][j] <= 9` +* Sum of `grid` is equal to `9`. + +## Solution + +```kotlin +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min + +class Solution { + fun minimumMoves(grid: Array): Int { + val a = grid[0][0] - 1 + val b = grid[0][1] - 1 + val c = grid[0][2] - 1 + val d = grid[1][0] - 1 + val f = grid[1][2] - 1 + val g = grid[2][0] - 1 + val h = grid[2][1] - 1 + val i = grid[2][2] - 1 + var minCost = Int.MAX_VALUE + for (x in min(a, 0)..max(a, 0)) { + for (y in min(c, 0)..max(c, 0)) { + for (z in min(i, 0)..max(i, 0)) { + for (t in min(g, 0)..max(g, 0)) { + val cost: Int = + abs(x) + abs(y) + abs(z) + abs(t) + abs((x - a)) + abs( + (y - c) + ) + abs((z - i)) + abs((t - g)) + abs((x - y + b + c)) + abs( + (y - z + i + f) + ) + abs((z - t + g + h)) + abs((t - x + a + d)) + if (cost < minCost) { + minCost = cost + } + } + } + } + } + return minCost + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2851_string_transformation/readme.md b/src/main/kotlin/g2801_2900/s2851_string_transformation/readme.md new file mode 100644 index 00000000..6eeae9b3 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2851_string_transformation/readme.md @@ -0,0 +1,141 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2851\. String Transformation + +Hard + +You are given two strings `s` and `t` of equal length `n`. You can perform the following operation on the string `s`: + +* Remove a **suffix** of `s` of length `l` where `0 < l < n` and append it at the start of `s`. + For example, let `s = 'abcd'` then in one operation you can remove the suffix `'cd'` and append it in front of `s` making `s = 'cdab'`. + +You are also given an integer `k`. Return _the number of ways in which_ `s` _can be transformed into_ `t` _in **exactly**_ `k` _operations._ + +Since the answer can be large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** s = "abcd", t = "cdab", k = 2 + +**Output:** 2 + +**Explanation:** + +First way: + +In first operation, choose suffix from index = 3, so resulting s = "dabc". + +In second operation, choose suffix from index = 3, so resulting s = "cdab". + +Second way: + +In first operation, choose suffix from index = 1, so resulting s = "bcda". + +In second operation, choose suffix from index = 1, so resulting s = "cdab". + +**Example 2:** + +**Input:** s = "ababab", t = "ababab", k = 1 + +**Output:** 2 + +**Explanation:** + +First way: + +Choose suffix from index = 2, so resulting s = "ababab". + +Second way: + +Choose suffix from index = 4, so resulting s = "ababab". + +**Constraints:** + +* 2 <= s.length <= 5 * 105 +* 1 <= k <= 1015 +* `s.length == t.length` +* `s` and `t` consist of only lowercase English alphabets. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private lateinit var g: Array + + fun numberOfWays(s: String, t: String, k: Long): Int { + val n = s.length + val v = kmp(s + s, t) + g = arrayOf(longArrayOf((v - 1).toLong(), v.toLong()), longArrayOf((n - v).toLong(), (n - 1 - v).toLong())) + val f = qmi(k) + return if (s == t) f[0][0].toInt() else f[0][1].toInt() + } + + private fun kmp(s: String, p: String): Int { + var s = s + var p = p + val n = p.length + val m = s.length + s = "#$s" + p = "#$p" + val ne = IntArray(n + 1) + var j = 0 + for (i in 2..n) { + while (j > 0 && p[i] != p[j + 1]) { + j = ne[j] + } + if (p[i] == p[j + 1]) { + j++ + } + ne[i] = j + } + var cnt = 0 + j = 0 + for (i in 1..m) { + while (j > 0 && s[i] != p[j + 1]) { + j = ne[j] + } + if (s[i] == p[j + 1]) { + j++ + } + if (j == n) { + if (i - n + 1 <= n) { + cnt++ + } + j = ne[j] + } + } + return cnt + } + + private fun mul(c: Array, a: Array, b: Array) { + val t = Array(2) { LongArray(2) } + for (i in 0..1) { + for (j in 0..1) { + for (k in 0..1) { + val mod = 1e9.toInt() + 7 + t[i][j] = (t[i][j] + a[i][k] * b[k][j]) % mod + } + } + } + for (i in 0..1) { + System.arraycopy(t[i], 0, c[i], 0, 2) + } + } + + private fun qmi(k: Long): Array { + var k = k + val f = Array(2) { LongArray(2) } + f[0][0] = 1 + while (k > 0) { + if ((k and 1L) == 1L) { + mul(f, f, g) + } + mul(g, g, g) + k = k shr 1 + } + return f + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array/readme.md b/src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array/readme.md new file mode 100644 index 00000000..c749769c --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2855\. Minimum Right Shifts to Sort the Array + +Easy + +You are given a **0-indexed** array `nums` of length `n` containing **distinct** positive integers. Return _the **minimum** number of **right shifts** required to sort_ `nums` _and_ `-1` _if this is not possible._ + +A **right shift** is defined as shifting the element at index `i` to index `(i + 1) % n`, for all indices. + +**Example 1:** + +**Input:** nums = [3,4,5,1,2] + +**Output:** 2 + +**Explanation:** + +After the first right shift, nums = [2,3,4,5,1]. + +After the second right shift, nums = [1,2,3,4,5]. + +Now nums is sorted; therefore the answer is 2. + +**Example 2:** + +**Input:** nums = [1,3,5] + +**Output:** 0 + +**Explanation:** nums is already sorted therefore, the answer is 0. + +**Example 3:** + +**Input:** nums = [2,1,4] + +**Output:** -1 + +**Explanation:** It's impossible to sort the array using right shifts. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` +* `nums` contains distinct integers. + +## Solution + +```kotlin +class Solution { + fun minimumRightShifts(nums: List): Int { + var i = 1 + while (i < nums.size) { + if (nums[i] < nums[i - 1]) { + break + } + i++ + } + if (nums.size == i) { + return 0 + } else { + var k = i + 1 + while (k < nums.size) { + if (nums[k] <= nums[k - 1]) { + break + } + k++ + } + if (k == nums.size && nums[k - 1] < nums[0]) { + return nums.size - i + } + return -1 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2856_minimum_array_length_after_pair_removals/readme.md b/src/main/kotlin/g2801_2900/s2856_minimum_array_length_after_pair_removals/readme.md new file mode 100644 index 00000000..57d7bb84 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2856_minimum_array_length_after_pair_removals/readme.md @@ -0,0 +1,94 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2856\. Minimum Array Length After Pair Removals + +Medium + +You are given a **0-indexed** **sorted** array of integers `nums`. + +You can perform the following operation any number of times: + +* Choose **two** indices, `i` and `j`, where `i < j`, such that `nums[i] < nums[j]`. +* Then, remove the elements at indices `i` and `j` from `nums`. The remaining elements retain their original order, and the array is re-indexed. + +Return _an integer that denotes the **minimum** length of_ `nums` _after performing the operation any number of times (**including zero**)._ + +Note that `nums` is sorted in **non-decreasing** order. + +**Example 1:** + +**Input:** nums = [1,3,4,9] + +**Output:** 0 + +**Explanation:** Initially, nums = [1, 3, 4, 9]. + +In the first operation, we can choose index 0 and 1 because nums[0] < nums[1] <=> 1 < 3. + +Remove indices 0 and 1, and nums becomes [4, 9]. + +For the next operation, we can choose index 0 and 1 because nums[0] < nums[1] <=> 4 < 9. + +Remove indices 0 and 1, and nums becomes an empty array []. Hence, the minimum length achievable is 0. + +**Example 2:** + +**Input:** nums = [2,3,6,9] + +**Output:** 0 + +**Explanation:** Initially, nums = [2, 3, 6, 9]. + +In the first operation, we can choose index 0 and 2 because nums[0] < nums[2] <=> 2 < 6. + +Remove indices 0 and 2, and nums becomes [3, 9]. + +For the next operation, we can choose index 0 and 1 because nums[0] < nums[1] <=> 3 < 9. + +Remove indices 0 and 1, and nums becomes an empty array []. Hence, the minimum length achievable is 0. + +**Example 3:** + +**Input:** nums = [1,1,2] + +**Output:** 1 + +**Explanation:** Initially, nums = [1, 1, 2]. + +In an operation, we can choose index 0 and 2 because nums[0] < nums[2] <=> 1 < 2. + +Remove indices 0 and 2, and nums becomes [1]. + +It is no longer possible to perform an operation on the array. Hence, the minimum achievable length is 1. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* `nums` is sorted in **non-decreasing** order. + +## Solution + +```kotlin +class Solution { + fun minLengthAfterRemovals(nums: List): Int { + val n = nums.size + var i = 0 + var j = if (n % 2 == 0) { + n / 2 + } else { + n / 2 + 1 + } + var count = 0 + while (i < n / 2 && j < n) { + if (nums[i] < nums[j]) { + count += 2 + } + i++ + j++ + } + return n - count + } +} +``` \ No newline at end of file