diff --git a/README.md b/README.md index dca37598..66b1063d 100644 --- a/README.md +++ b/README.md @@ -1821,6 +1821,30 @@ | 2798 |[Number of Employees Who Met the Target](src/main/kotlin/g2701_2800/s2798_number_of_employees_who_met_the_target)| Easy | Array, Enumeration | 153 | 92.50 | 2791 |[Count Paths That Can Form a Palindrome in a Tree](src/main/kotlin/g2701_2800/s2791_count_paths_that_can_form_a_palindrome_in_a_tree)| Hard | Dynamic_Programming, Tree, Bit_Manipulation, Bitmask, Depth_First_Search | 683 | 100.00 | 2790 |[Maximum Number of Groups With Increasing Length](src/main/kotlin/g2701_2800/s2790_maximum_number_of_groups_with_increasing_length)| Hard | Array, Math, Sorting, Greedy, Binary_Search | 545 | 100.00 +| 2789 |[Largest Element in an Array after Merge Operations](src/main/kotlin/g2701_2800/s2789_largest_element_in_an_array_after_merge_operations)| Medium | Array, Greedy, Prefix_Sum | 683 | 73.68 +| 2788 |[Split Strings by Separator](src/main/kotlin/g2701_2800/s2788_split_strings_by_separator)| Easy | Array, String | 314 | 85.45 +| 2787 |[Ways to Express an Integer as Sum of Powers](src/main/kotlin/g2701_2800/s2787_ways_to_express_an_integer_as_sum_of_powers)| Medium | Dynamic_Programming | 152 | 100.00 +| 2786 |[Visit Array Positions to Maximize Score](src/main/kotlin/g2701_2800/s2786_visit_array_positions_to_maximize_score)| Medium | Array, Dynamic_Programming | 625 | 84.00 +| 2785 |[Sort Vowels in a String](src/main/kotlin/g2701_2800/s2785_sort_vowels_in_a_string)| Medium | String, Sorting | 233 | 100.00 +| 2784 |[Check if Array is Good](src/main/kotlin/g2701_2800/s2784_check_if_array_is_good)| Easy | Array, Hash_Table, Sorting | 177 | 88.89 +| 2781 |[Length of the Longest Valid Substring](src/main/kotlin/g2701_2800/s2781_length_of_the_longest_valid_substring)| Hard | Array, String, Hash_Table, Sliding_Window | 647 | 100.00 +| 2780 |[Minimum Index of a Valid Split](src/main/kotlin/g2701_2800/s2780_minimum_index_of_a_valid_split)| Medium | Array, Hash_Table, Sorting | 640 | 91.67 +| 2779 |[Maximum Beauty of an Array After Applying Operation](src/main/kotlin/g2701_2800/s2779_maximum_beauty_of_an_array_after_applying_operation)| Medium | Array, Sorting, Binary_Search, Sliding_Window | 649 | 96.97 +| 2778 |[Sum of Squares of Special Elements](src/main/kotlin/g2701_2800/s2778_sum_of_squares_of_special_elements)| Easy | Array, Simulation | 183 | 86.44 +| 2772 |[Apply Operations to Make All Array Elements Equal to Zero](src/main/kotlin/g2701_2800/s2772_apply_operations_to_make_all_array_elements_equal_to_zero)| Medium | Array, Prefix_Sum | 578 | 97.06 +| 2771 |[Longest Non-decreasing Subarray From Two Arrays](src/main/kotlin/g2701_2800/s2771_longest_non_decreasing_subarray_from_two_arrays)| Medium | Array, Dynamic_Programming | 665 | 96.88 +| 2770 |[Maximum Number of Jumps to Reach the Last Index](src/main/kotlin/g2701_2800/s2770_maximum_number_of_jumps_to_reach_the_last_index)| Medium | Array, Dynamic_Programming | 325 | 51.16 +| 2769 |[Find the Maximum Achievable Number](src/main/kotlin/g2701_2800/s2769_find_the_maximum_achievable_number)| Easy | Math | 134 | 97.89 +| 2768 |[Number of Black Blocks](src/main/kotlin/g2701_2800/s2768_number_of_black_blocks)| Medium | Array, Hash_Table, Enumeration | 719 | 100.00 +| 2767 |[Partition String Into Minimum Beautiful Substrings](src/main/kotlin/g2701_2800/s2767_partition_string_into_minimum_beautiful_substrings)| Medium | String, Hash_Table, Dynamic_Programming, Backtracking | 162 | 96.00 +| 2766 |[Relocate Marbles](src/main/kotlin/g2701_2800/s2766_relocate_marbles)| Medium | Array, Hash_Table, Sorting, Simulation | 1038 | 100.00 +| 2765 |[Longest Alternating Subarray](src/main/kotlin/g2701_2800/s2765_longest_alternating_subarray)| Easy | Array, Enumeration | 191 | 97.92 +| 2763 |[Sum of Imbalance Numbers of All Subarrays](src/main/kotlin/g2701_2800/s2763_sum_of_imbalance_numbers_of_all_subarrays)| Hard | Array, Hash_Table, Ordered_Set | 417 | 95.24 +| 2762 |[Continuous Subarrays](src/main/kotlin/g2701_2800/s2762_continuous_subarrays)| Medium | Array, Heap_Priority_Queue, Sliding_Window, Ordered_Set, Queue, Monotonic_Queue | 492 | 100.00 +| 2761 |[Prime Pairs With Target Sum](src/main/kotlin/g2701_2800/s2761_prime_pairs_with_target_sum)| Medium | Array, Math, Enumeration, Number_Theory | 537 | 100.00 +| 2760 |[Longest Even Odd Subarray With Threshold](src/main/kotlin/g2701_2800/s2760_longest_even_odd_subarray_with_threshold)| Easy | Array, Sliding_Window | 285 | 95.45 +| 2751 |[Robot Collisions](src/main/kotlin/g2701_2800/s2751_robot_collisions)| Hard | Array, Sorting, Stack, Simulation | 1049 | 100.00 +| 2750 |[Ways to Split Array Into Good Subarrays](src/main/kotlin/g2701_2800/s2750_ways_to_split_array_into_good_subarrays)| Medium | Array, Dynamic_Programming, Math | 916 | 100.00 | 2749 |[Minimum Operations to Make the Integer Zero](src/main/kotlin/g2701_2800/s2749_minimum_operations_to_make_the_integer_zero)| Medium | Bit_Manipulation, Brainteaser | 132 | 91.67 | 2748 |[Number of Beautiful Pairs](src/main/kotlin/g2701_2800/s2748_number_of_beautiful_pairs)| Easy | Array, Math, Number_Theory | 227 | 100.00 | 2747 |[Count Zero Request Servers](src/main/kotlin/g2701_2800/s2747_count_zero_request_servers)| Medium | Array, Hash_Table, Sorting, Sliding_Window | 991 | 100.00 diff --git a/src/main/kotlin/g2701_2800/s2750_ways_to_split_array_into_good_subarrays/readme.md b/src/main/kotlin/g2701_2800/s2750_ways_to_split_array_into_good_subarrays/readme.md new file mode 100644 index 00000000..dcb8eaf8 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2750_ways_to_split_array_into_good_subarrays/readme.md @@ -0,0 +1,64 @@ +[![](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) + +## 2750\. Ways to Split Array Into Good Subarrays + +Medium + +You are given a binary array `nums`. + +A subarray of an array is **good** if it contains **exactly** **one** element with the value `1`. + +Return _an integer denoting the number of ways to split the array_ `nums` _into **good** subarrays_. As the number may be too large, return it **modulo** 109 + 7. + +A subarray is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [0,1,0,0,1] + +**Output:** 3 + +**Explanation:** There are 3 ways to split nums into good subarrays: +- \[0,1] [0,0,1] +- \[0,1,0] [0,1] +- \[0,1,0,0] [1] + +**Example 2:** + +**Input:** nums = [0,1,0] + +**Output:** 1 + +**Explanation:** There is 1 way to split nums into good subarrays: - [0,1,0] + +**Constraints:** + +* 1 <= nums.length <= 105 +* `0 <= nums[i] <= 1` + +## Solution + +```kotlin +class Solution { + fun numberOfGoodSubarraySplits(nums: IntArray): Int { + val res: MutableList = ArrayList() + val modulo = 1000000007L + for (i in nums.indices) { + if (nums[i] == 1) res.add(i) + } + var ans: Long = 0 + if (res.isNotEmpty()) ans = 1 + var kanishk = ans + for (i in res.size - 2 downTo 0) { + val leftInd = res[i] + val rightInd = res[i + 1] + val df = rightInd - leftInd + val mul = df.toLong() % modulo * kanishk % modulo % modulo + kanishk = mul + ans = mul + } + return ans.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2751_robot_collisions/readme.md b/src/main/kotlin/g2701_2800/s2751_robot_collisions/readme.md new file mode 100644 index 00000000..faac23b3 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2751_robot_collisions/readme.md @@ -0,0 +1,126 @@ +[![](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) + +## 2751\. Robot Collisions + +Hard + +There are `n` **1-indexed** robots, each having a position on a line, health, and movement direction. + +You are given **0-indexed** integer arrays `positions`, `healths`, and a string `directions` (`directions[i]` is either **'L'** for **left** or **'R'** for **right**). All integers in `positions` are **unique**. + +All robots start moving on the line **simultaneously** at the **same speed** in their given directions. If two robots ever share the same position while moving, they will **collide**. + +If two robots collide, the robot with **lower health** is **removed** from the line, and the health of the other robot **decreases** **by one**. The surviving robot continues in the **same** direction it was going. If both robots have the **same** health, they are both removed from the line. + +Your task is to determine the **health** of the robots that survive the collisions, in the same **order** that the robots were given, i.e. final heath of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array. + +Return _an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur._ + +**Note:** The positions may be unsorted. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/05/15/image-20230516011718-12.png) + +**Input:** positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR" + +**Output:** [2,17,9,15,10] + +**Explanation:** No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10]. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/05/15/image-20230516004433-7.png) + +**Input:** positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL" + +**Output:** [14] + +**Explanation:** There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14]. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2023/05/15/image-20230516005114-9.png) + +**Input:** positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL" + +**Output:** [] + +**Explanation:** Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, []. + +**Constraints:** + +* 1 <= positions.length == healths.length == directions.length == n <= 105 +* 1 <= positions[i], healths[i] <= 109 +* `directions[i] == 'L'` or `directions[i] == 'R'` +* All values in `positions` are distinct + +## Solution + +```kotlin +import java.util.ArrayDeque + +class Solution { + fun survivedRobotsHealths(pos: IntArray, h: IntArray, dir: String): List { + val a = Array(pos.size) { IntArray(4) { 0 } } + for (i in pos.indices) { + a[i][0] = pos[i] + a[i][1] = h[i] + a[i][2] = if (dir[i] == 'R') 1 else 0 + a[i][3] = i + } + a.sortWith(compareBy { it[0] }) + val q = ArrayDeque() + for (i in a.indices) { + if (q.isEmpty() || a[i][2] == 1) { + q.push(i) + } else { + var prev = a[q.peek()] + if (prev[2] == 1) { + if (a[i][1] == prev[1]) { + q.pop() + continue + } else { + while (true) { + if (a[i][1] == prev[1]) { + q.pop() + break + } + if (prev[1] > a[i][1]) { + prev[1] -= 1 + break + } else { + q.pop() + a[i][1] -= 1 + if (q.isEmpty() || a[q.peek()][2] == 0) { + q.push(i) + break + } else { + prev = a[q.peek()] + } + } + } + } + } else { + q.push(i) + } + } + } + val b = Array(q.size) { IntArray(2) { 0 } } + var j = 0 + while (q.isNotEmpty()) { + val n = q.pop() + b[j][0] = a[n][1] + b[j][1] = a[n][3] + j++ + } + b.sortWith(compareBy { it[1] }) + val res = mutableListOf() + for (element in b) { + res.add(element[0]) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2760_longest_even_odd_subarray_with_threshold/readme.md b/src/main/kotlin/g2701_2800/s2760_longest_even_odd_subarray_with_threshold/readme.md new file mode 100644 index 00000000..30392f56 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2760_longest_even_odd_subarray_with_threshold/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) + +## 2760\. Longest Even Odd Subarray With Threshold + +Easy + +You are given a **0-indexed** integer array `nums` and an integer `threshold`. + +Find the length of the **longest subarray** of `nums` starting at index `l` and ending at index `r` `(0 <= l <= r < nums.length)` that satisfies the following conditions: + +* `nums[l] % 2 == 0` +* For all indices `i` in the range `[l, r - 1]`, `nums[i] % 2 != nums[i + 1] % 2` +* For all indices `i` in the range `[l, r]`, `nums[i] <= threshold` + +Return _an integer denoting the length of the longest such subarray._ + +**Note:** A **subarray** is a contiguous non-empty sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [3,2,5,4], threshold = 5 + +**Output:** 3 + +**Explanation:** + +In this example, we can select the subarray that starts at l = 1 and ends at r = 3 => [2,5,4]. This subarray satisfies the conditions. + +Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length. + +**Example 2:** + +**Input:** nums = [1,2], threshold = 2 + +**Output:** 1 + +**Explanation:** + +In this example, we can select the subarray that starts at l = 1 and ends at r = 1 => [2]. + +It satisfies all the conditions and we can show that 1 is the maximum possible achievable length. + +**Example 3:** + +**Input:** nums = [2,3,4,5], threshold = 4 + +**Output:** 3 + +**Explanation:** + +In this example, we can select the subarray that starts at l = 0 and ends at r = 2 => [2,3,4]. + +It satisfies all the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` +* `1 <= threshold <= 100` + +## Solution + +```kotlin +class Solution { + fun longestAlternatingSubarray(nums: IntArray, threshold: Int): Int { + var maxLength = 0 + var i = 0 + while (i < nums.size) { + if (nums[i] % 2 == 0 && nums[i] <= threshold) { + var length = 1 + var j = i + 1 + while (j < nums.size && + nums[j] <= threshold && + nums[j] % 2 != nums[j - 1] % 2 + ) { + length++ + j++ + } + maxLength = maxLength.coerceAtLeast(length) + i = j - 1 + } + i++ + } + return maxLength + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2761_prime_pairs_with_target_sum/readme.md b/src/main/kotlin/g2701_2800/s2761_prime_pairs_with_target_sum/readme.md new file mode 100644 index 00000000..3987e3ba --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2761_prime_pairs_with_target_sum/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) + +## 2761\. Prime Pairs With Target Sum + +Medium + +You are given an integer `n`. We say that two integers `x` and `y` form a prime number pair if: + +* `1 <= x <= y <= n` +* `x + y == n` +* `x` and `y` are prime numbers + +Return _the 2D sorted list of prime number pairs_ [xi, yi]. The list should be sorted in **increasing** order of xi. If there are no prime number pairs at all, return _an empty array_. + +**Note:** A prime number is a natural number greater than `1` with only two factors, itself and `1`. + +**Example 1:** + +**Input:** n = 10 + +**Output:** [[3,7],[5,5]] + +**Explanation:** + +In this example, there are two prime pairs that satisfy the criteria. + +These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement. + +**Example 2:** + +**Input:** n = 2 + +**Output:** [] + +**Explanation:** + +We can show that there is no prime number pair that gives a sum of 2, so we return an empty array. + +**Constraints:** + +* 1 <= n <= 106 + +## Solution + +```kotlin +class Solution { + fun findPrimePairs(n: Int): List> { + val answer: MutableList> = ArrayList() + for (a in list) { + val other = n - a + if (other < n / 2 || a > n / 2) break + if (primes.contains(other)) answer.add(listOf(a, other)) + } + return answer + } + + companion object { + private val primes: HashSet = HashSet() + private val list: MutableList = ArrayList() + + init { + val m = 1000001 + val visited = BooleanArray(m) + for (i in 2 until m) { + if (!visited[i]) { + primes.add(i) + list.add(i) + var j: Int = i + while (j < m) { + visited[j] = true + j += i + } + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2762_continuous_subarrays/readme.md b/src/main/kotlin/g2701_2800/s2762_continuous_subarrays/readme.md new file mode 100644 index 00000000..f23b7f53 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2762_continuous_subarrays/readme.md @@ -0,0 +1,86 @@ +[![](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) + +## 2762\. Continuous Subarrays + +Medium + +You are given a **0-indexed** integer array `nums`. A subarray of `nums` is called **continuous** if: + +* Let `i`, `i + 1`, ..., `j` be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2. + +Return _the total number of **continuous** subarrays._ + +A subarray is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [5,4,2,4] + +**Output:** 8 + +**Explanation:** + +Continuous subarray of size 1: [5], [4], [2], [4]. + +Continuous subarray of size 2: [5,4], [4,2], [2,4]. + +Continuous subarray of size 3: [4,2,4]. + +Thereare no subarrys of size 4. + +Total continuous subarrays = 4 + 3 + 1 = 8. + +It can be shown that there are no more continuous subarrays. + +**Example 2:** + +**Input:** nums = [1,2,3] + +**Output:** 6 + +**Explanation:** + +Continuous subarray of size 1: [1], [2], [3]. + +Continuous subarray of size 2: [1,2], [2,3]. + +Continuous subarray of size 3: [1,2,3]. + +Total continuous subarrays = 3 + 2 + 1 = 6. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +import java.util.TreeMap + +class Solution { + fun continuousSubarrays(nums: IntArray): Long { + var left = 0 + var right = 0 + var total = 0L + val tree = TreeMap() + val n = nums.size + while (right < n) { + if (!tree.containsKey(nums[right])) { + tree[nums[right]] = 0 + } + tree[nums[right]] = tree[nums[right]]!! + 1 + while (kotlin.math.abs(tree.lastKey() - nums[right]) > 2 || Math.abs(tree.firstKey() - nums[right]) > 2) { + val keyL = nums[left] + tree[keyL] = tree[keyL]!! - 1 + if (tree[keyL] == 0) tree.remove(keyL) + left++ + } + total += right - left + 1 + right++ + } + return total + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2763_sum_of_imbalance_numbers_of_all_subarrays/readme.md b/src/main/kotlin/g2701_2800/s2763_sum_of_imbalance_numbers_of_all_subarrays/readme.md new file mode 100644 index 00000000..22152c44 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2763_sum_of_imbalance_numbers_of_all_subarrays/readme.md @@ -0,0 +1,80 @@ +[![](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) + +## 2763\. Sum of Imbalance Numbers of All Subarrays + +Hard + +The **imbalance number** of a **0-indexed** integer array `arr` of length `n` is defined as the number of indices in `sarr = sorted(arr)` such that: + +* `0 <= i < n - 1`, and +* `sarr[i+1] - sarr[i] > 1` + +Here, `sorted(arr)` is the function that returns the sorted version of `arr`. + +Given a **0-indexed** integer array `nums`, return _the **sum of imbalance numbers** of all its **subarrays**_. + +A **subarray** is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [2,3,1,4] + +**Output:** 3 + +**Explanation:** There are 3 subarrays with non-zero imbalance numbers: +- Subarray [3, 1] with an imbalance number of 1. +- Subarray [3, 1, 4] with an imbalance number of 1. +- Subarray [1, 4] with an imbalance number of 1. + +The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 3. + +**Example 2:** + +**Input:** nums = [1,3,3,3,5] + +**Output:** 8 + +**Explanation:** There are 7 subarrays with non-zero imbalance numbers: +- Subarray [1, 3] with an imbalance number of 1. +- Subarray [1, 3, 3] with an imbalance number of 1. +- Subarray [1, 3, 3, 3] with an imbalance number of 1. +- Subarray [1, 3, 3, 3, 5] with an imbalance number of 2. +- Subarray [3, 3, 3, 5] with an imbalance number of 1. +- Subarray [3, 3, 5] with an imbalance number of 1. +- Subarray [3, 5] with an imbalance number of 1. + +The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 8. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* `1 <= nums[i] <= nums.length` + +## Solution + +```kotlin +class Solution { + fun sumImbalanceNumbers(nums: IntArray): Int { + val n = nums.size + var ans = 0 + for (i in 0 until n) { + val s: MutableSet = HashSet() + var curr = 0 + for (j in i until n) { + val x = nums[j] + if (s.contains(x)) { + // do nothing + } else if (s.contains(x - 1) && s.contains(x + 1)) { + curr-- + } else if (!s.contains(x - 1) && !s.contains(x + 1) && s.isNotEmpty()) { + curr++ + } + s.add(x) + ans += curr + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2765_longest_alternating_subarray/readme.md b/src/main/kotlin/g2701_2800/s2765_longest_alternating_subarray/readme.md new file mode 100644 index 00000000..c0081f0a --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2765_longest_alternating_subarray/readme.md @@ -0,0 +1,68 @@ +[![](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) + +## 2765\. Longest Alternating Subarray + +Easy + +You are given a **0-indexed** integer array `nums`. A subarray `s` of length `m` is called **alternating** if: + +* `m` is greater than `1`. +* s1 = s0 + 1. +* The **0-indexed** subarray `s` looks like [s0, s1, s0, s1,...,s(m-1) % 2]. In other words, s1 - s0 = 1, s2 - s1 = -1, s3 - s2 = 1, s4 - s3 = -1, and so on up to s[m - 1] - s[m - 2] = (-1)m. + +Return _the maximum length of all **alternating** subarrays present in_ `nums` _or_ `-1` _if no such subarray exists__._ + +A subarray is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [2,3,4,3,4] + +**Output:** 4 + +**Explanation:** The alternating subarrays are [3,4], [3,4,3], and [3,4,3,4]. The longest of these is [3,4,3,4], which is of length 4. + +**Example 2:** + +**Input:** nums = [4,5,6] + +**Output:** 2 + +**Explanation:** [4,5] and [5,6] are the only two alternating subarrays. They are both of length 2. + +**Constraints:** + +* `2 <= nums.length <= 100` +* 1 <= nums[i] <= 104 + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun alternatingSubarray(nums: IntArray): Int { + var result = -1 + var prious = 0 + var sum = 1 + for (i in 1..nums.lastIndex) { + val s = nums[i] - nums[i - 1] + if (abs(s) != 1) { + sum = 1 + continue + } + if (s == prious) { + sum = 2 + } + if (s != prious) { + if (s != if (sum % 2 == 0) -1 else 1) continue + sum++ + prious = s + } + result = maxOf(result, sum) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2766_relocate_marbles/readme.md b/src/main/kotlin/g2701_2800/s2766_relocate_marbles/readme.md new file mode 100644 index 00000000..78bed57f --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2766_relocate_marbles/readme.md @@ -0,0 +1,73 @@ +[![](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) + +## 2766\. Relocate Marbles + +Medium + +You are given a **0-indexed** integer array `nums` representing the initial positions of some marbles. You are also given two **0-indexed** integer arrays `moveFrom` and `moveTo` of **equal** length. + +Throughout `moveFrom.length` steps, you will change the positions of the marbles. On the ith step, you will move **all** marbles at position `moveFrom[i]` to position `moveTo[i]`. + +After completing all the steps, return _the sorted list of **occupied** positions_. + +**Notes:** + +* We call a position **occupied** if there is at least one marble in that position. +* There may be multiple marbles in a single position. + +**Example 1:** + +**Input:** nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5] + +**Output:** [5,6,8,9] + +**Explanation:** Initially, the marbles are at positions 1,6,7,8. + +At the i = 0th step, we move the marbles at position 1 to position 2. Then, positions 2,6,7,8 are occupied. + +At the i = 1st step, we move the marbles at position 7 to position 9. Then, positions 2,6,8,9 are occupied. + +At the i = 2nd step, we move the marbles at position 2 to position 5. Then, positions 5,6,8,9 are occupied. + +At the end, the final positions containing at least one marbles are [5,6,8,9]. + +**Example 2:** + +**Input:** nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2] + +**Output:** [2] + +**Explanation:** Initially, the marbles are at positions [1,1,3,3]. + +At the i = 0th step, we move all the marbles at position 1 to position 2. Then, the marbles are at positions [2,2,3,3]. + +At the i = 1st step, we move all the marbles at position 3 to position 2. Then, the marbles are at positions [2,2,2,2]. + +Since 2 is the only occupied position, we return [2]. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= moveFrom.length <= 105 +* `moveFrom.length == moveTo.length` +* 1 <= nums[i], moveFrom[i], moveTo[i] <= 109 +* The test cases are generated such that there is at least a marble in `moveFrom[i]` at the moment we want to apply the ith move. + +## Solution + +```kotlin +class Solution { + fun relocateMarbles(nums: IntArray, moveFrom: IntArray, moveTo: IntArray): List { + val s = HashSet() + nums.forEach { s.add(it) } + for (i in moveTo.indices) { + if (s.contains(moveFrom[i])) { + s.remove(moveFrom[i]) + s.add(moveTo[i]) + } + } + return s.toList().sorted() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2767_partition_string_into_minimum_beautiful_substrings/readme.md b/src/main/kotlin/g2701_2800/s2767_partition_string_into_minimum_beautiful_substrings/readme.md new file mode 100644 index 00000000..f2dc50eb --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2767_partition_string_into_minimum_beautiful_substrings/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) + +## 2767\. Partition String Into Minimum Beautiful Substrings + +Medium + +Given a binary string `s`, partition the string into one or more **substrings** such that each substring is **beautiful**. + +A string is **beautiful** if: + +* It doesn't contain leading zeros. +* It's the **binary** representation of a number that is a power of `5`. + +Return _the **minimum** number of substrings in such partition._ If it is impossible to partition the string `s` into beautiful substrings, return `-1`. + +A **substring** is a contiguous sequence of characters in a string. + +**Example 1:** + +**Input:** s = "1011" + +**Output:** 2 + +**Explanation:** We can paritition the given string into ["101", "1"]. +- The string "101" does not contain leading zeros and is the binary representation of integer 51 = 5. +- The string "1" does not contain leading zeros and is the binary representation of integer 50 = 1. + +It can be shown that 2 is the minimum number of beautiful substrings that s can be partitioned into. + +**Example 2:** + +**Input:** s = "111" + +**Output:** 3 + +**Explanation:** We can paritition the given string into ["1", "1", "1"]. +- The string "1" does not contain leading zeros and is the binary representation of integer 50 = 1. + +It can be shown that 3 is the minimum number of beautiful substrings that s can be partitioned into. + +**Example 3:** + +**Input:** s = "0" + +**Output:** -1 + +**Explanation:** We can not partition the given string into beautiful substrings. + +**Constraints:** + +* `1 <= s.length <= 15` +* `s[i]` is either `'0'` or `'1'`. + +## Solution + +```kotlin +class Solution { + fun minimumBeautifulSubstrings(s: String): Int { + val set: MutableSet = HashSet() + set.add("1") + set.add("101") + set.add("11001") + set.add("1111101") + set.add("1001110001") + set.add("110000110101") + set.add("11110100001001") + val result = minimumBeautifulSubstringsHelper(s, 0, set, 0) + return if (result == Int.MAX_VALUE) { + -1 + } else result + } + + private fun minimumBeautifulSubstringsHelper(s: String, index: Int, set: Set, count: Int): Int { + if (index >= s.length) { + return count + } + var minResult = Int.MAX_VALUE + for (i in index..s.length) { + if (set.contains(s.substring(index, i))) { + val result = minimumBeautifulSubstringsHelper(s, i, set, count + 1) + minResult = minResult.coerceAtMost(result) + } + } + return minResult + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2768_number_of_black_blocks/readme.md b/src/main/kotlin/g2701_2800/s2768_number_of_black_blocks/readme.md new file mode 100644 index 00000000..f16f3178 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2768_number_of_black_blocks/readme.md @@ -0,0 +1,81 @@ +[![](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) + +## 2768\. Number of Black Blocks + +Medium + +You are given two integers `m` and `n` representing the dimensions of a **0-indexed** `m x n` grid. + +You are also given a **0-indexed** 2D integer matrix `coordinates`, where `coordinates[i] = [x, y]` indicates that the cell with coordinates `[x, y]` is colored **black**. All cells in the grid that do not appear in `coordinates` are **white**. + +A block is defined as a `2 x 2` submatrix of the grid. More formally, a block with cell `[x, y]` as its top-left corner where `0 <= x < m - 1` and `0 <= y < n - 1` contains the coordinates `[x, y]`, `[x + 1, y]`, `[x, y + 1]`, and `[x + 1, y + 1]`. + +Return _a **0-indexed** integer array_ `arr` _of size_ `5` _such that_ `arr[i]` _is the number of blocks that contains exactly_ `i` _**black** cells_. + +**Example 1:** + +**Input:** m = 3, n = 3, coordinates = \[\[0,0]] + +**Output:** [3,1,0,0,0] + +**Explanation:** The grid looks like this: ![](https://assets.leetcode.com/uploads/2023/06/18/screen-shot-2023-06-18-at-44656-am.png) + +There is only 1 block with one black cell, and it is the block starting with cell [0,0]. + +The other 3 blocks start with cells [0,1], [1,0] and [1,1]. They all have zero black cells. + +Thus, we return [3,1,0,0,0]. + +**Example 2:** + +**Input:** m = 3, n = 3, coordinates = \[\[0,0],[1,1],[0,2]] + +**Output:** [0,2,2,0,0] + +**Explanation:** The grid looks like this: ![](https://assets.leetcode.com/uploads/2023/06/18/screen-shot-2023-06-18-at-45018-am.png) + +There are 2 blocks with two black cells (the ones starting with cell coordinates [0,0] and [0,1]). + +The other 2 blocks have starting cell coordinates of [1,0] and [1,1]. They both have 1 black cell. + +Therefore, we return [0,2,2,0,0]. + +**Constraints:** + +* 2 <= m <= 105 +* 2 <= n <= 105 +* 0 <= coordinates.length <= 104 +* `coordinates[i].length == 2` +* `0 <= coordinates[i][0] < m` +* `0 <= coordinates[i][1] < n` +* It is guaranteed that `coordinates` contains pairwise distinct coordinates. + +## Solution + +```kotlin +class Solution { + fun countBlackBlocks(m: Int, n: Int, coordinates: Array): LongArray { + val ans = LongArray(5) + val count: MutableMap = HashMap() + for (coordinate in coordinates) { + val x = coordinate[0] + val y = coordinate[1] + for (i in x until x + 2) { + for (j in y until y + 2) { + if (i - 1 >= 0 && i < m && j - 1 >= 0 && j < n) { + count.merge( + i * n + j, 1 + ) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) } + } + } + } + } + for (freq in count.values) { + ++ans[freq] + } + ans[0] = (m - 1L) * (n - 1) - ans.sum() + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2769_find_the_maximum_achievable_number/readme.md b/src/main/kotlin/g2701_2800/s2769_find_the_maximum_achievable_number/readme.md new file mode 100644 index 00000000..b7e0a8e6 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2769_find_the_maximum_achievable_number/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) + +## 2769\. Find the Maximum Achievable Number + +Easy + +You are given two integers, `num` and `t`. + +An integer `x` is called **achievable** if it can become equal to `num` after applying the following operation no more than `t` times: + +* Increase or decrease `x` by `1`, and simultaneously increase or decrease `num` by `1`. + +Return _the maximum possible achievable number_. It can be proven that there exists at least one achievable number. + +**Example 1:** + +**Input:** num = 4, t = 1 + +**Output:** 6 + +**Explanation:** + +The maximum achievable number is x = 6; it can become equal to num after performing this operation: + +1- Decrease x by 1, and increase num by 1. Now, x = 5 and num = 5. + +It can be proven that there is no achievable number larger than 6. + +**Example 2:** + +**Input:** num = 3, t = 2 + +**Output:** 7 + +**Explanation:** + +The maximum achievable number is x = 7; after performing these operations, x will equal num: + +1- Decrease x by 1, and increase num by 1. Now, x = 6 and num = 4. + +2- Decrease x by 1, and increase num by 1. Now, x = 5 and num = 5. + +It can be proven that there is no achievable number larger than 7. + +**Constraints:** + +* `1 <= num, t <= 50` + +## Solution + +```kotlin +class Solution { + fun theMaximumAchievableX(num: Int, t: Int): Int { + return num + t * 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2770_maximum_number_of_jumps_to_reach_the_last_index/readme.md b/src/main/kotlin/g2701_2800/s2770_maximum_number_of_jumps_to_reach_the_last_index/readme.md new file mode 100644 index 00000000..a91d927a --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2770_maximum_number_of_jumps_to_reach_the_last_index/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) + +## 2770\. Maximum Number of Jumps to Reach the Last Index + +Medium + +You are given a **0-indexed** array `nums` of `n` integers and an integer `target`. + +You are initially positioned at index `0`. In one step, you can jump from index `i` to any index `j` such that: + +* `0 <= i < j < n` +* `-target <= nums[j] - nums[i] <= target` + +Return _the **maximum number of jumps** you can make to reach index_ `n - 1`. + +If there is no way to reach index `n - 1`, return `-1`. + +**Example 1:** + +**Input:** nums = [1,3,6,4,1,2], target = 2 + +**Output:** 3 + +**Explanation:** + +To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: + +- Jump from index 0 to index 1. + +- Jump from index 1 to index 3. + +- Jump from index 3 to index 5. + +It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 3 jumps. + +Hence, the answer is 3. + +**Example 2:** + +**Input:** nums = [1,3,6,4,1,2], target = 3 + +**Output:** 5 + +**Explanation:** + +To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: + +- Jump from index 0 to index 1. + +- Jump from index 1 to index 2. + +- Jump from index 2 to index 3. + +- Jump from index 3 to index 4. + +- Jump from index 4 to index 5. + +It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 5 jumps. + +Hence, the answer is 5. + +**Example 3:** + +**Input:** nums = [1,3,6,4,1,2], target = 0 + +**Output:** -1 + +**Explanation:** It can be proven that there is no jumping sequence that goes from 0 to n - 1. Hence, the answer is -1. + +**Constraints:** + +* `2 <= nums.length == n <= 1000` +* -109 <= nums[i] <= 109 +* 0 <= target <= 2 * 109 + +## Solution + +```kotlin +class Solution { + private class Pair(var prev: Int, var len: Int) + + fun maximumJumps(nums: IntArray, target: Int): Int { + val arr = arrayOfNulls(nums.size) + arr[0] = Pair(0, 0) + for (i in 1 until nums.size) { + arr[i] = Pair(-1, 0) + for (j in i - 1 downTo 0) { + if (Math.abs(nums[i] - nums[j]) <= target && + arr[j]!!.prev != -1 && arr[j]!!.len + 1 > arr[i]!!.len + ) { + arr[i]!!.prev = j + arr[i]!!.len = arr[j]!!.len + 1 + } + } + } + return if (arr[nums.size - 1]!!.len > 0) arr[nums.size - 1]!!.len else -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2771_longest_non_decreasing_subarray_from_two_arrays/readme.md b/src/main/kotlin/g2701_2800/s2771_longest_non_decreasing_subarray_from_two_arrays/readme.md new file mode 100644 index 00000000..2685e9e0 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2771_longest_non_decreasing_subarray_from_two_arrays/readme.md @@ -0,0 +1,92 @@ +[![](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) + +## 2771\. Longest Non-decreasing Subarray From Two Arrays + +Medium + +You are given two **0-indexed** integer arrays `nums1` and `nums2` of length `n`. + +Let's define another **0-indexed** integer array, `nums3`, of length `n`. For each index `i` in the range `[0, n - 1]`, you can assign either `nums1[i]` or `nums2[i]` to `nums3[i]`. + +Your task is to maximize the length of the **longest non-decreasing subarray** in `nums3` by choosing its values optimally. + +Return _an integer representing the length of the **longest non-decreasing** subarray in_ `nums3`. + +**Note:** A **subarray** is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums1 = [2,3,1], nums2 = [1,2,1] + +**Output:** 2 + +**Explanation:** + +One way to construct nums3 is: + +nums3 = [nums1[0], nums2[1], nums2[2]] => [2,2,1]. + +The subarray starting from index 0 and ending at index 1, [2,2], forms a non-decreasing subarray of length 2. + +We can show that 2 is the maximum achievable length. + +**Example 2:** + +**Input:** nums1 = [1,3,2,1], nums2 = [2,2,3,4] + +**Output:** 4 + +**Explanation:** + +One way to construct nums3 is: + +nums3 = [nums1[0], nums2[1], nums2[2], nums2[3]] => [1,2,3,4]. + +The entire array forms a non-decreasing subarray of length 4, making it the maximum achievable length. + +**Example 3:** + +**Input:** nums1 = [1,1], nums2 = [2,2] + +**Output:** 2 + +**Explanation:** + +One way to construct nums3 is: + +nums3 = [nums1[0], nums1[1]] => [1,1]. + +The entire array forms a non-decreasing subarray of length 2, making it the maximum achievable length. + +**Constraints:** + +* 1 <= nums1.length == nums2.length == n <= 105 +* 1 <= nums1[i], nums2[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun maxNonDecreasingLength(nums1: IntArray, nums2: IntArray): Int { + var res = 1 + var dp1 = 1 + var dp2 = 1 + val n = nums1.size + var t11: Int + var t12: Int + var t21: Int + var t22: Int + for (i in 1 until n) { + t11 = if (nums1[i - 1] <= nums1[i]) dp1 + 1 else 1 + t12 = if (nums1[i - 1] <= nums2[i]) dp1 + 1 else 1 + t21 = if (nums2[i - 1] <= nums1[i]) dp2 + 1 else 1 + t22 = if (nums2[i - 1] <= nums2[i]) dp2 + 1 else 1 + dp1 = Math.max(t11, t21) + dp2 = Math.max(t12, t22) + res = Math.max(res, Math.max(dp1, dp2)) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2772_apply_operations_to_make_all_array_elements_equal_to_zero/readme.md b/src/main/kotlin/g2701_2800/s2772_apply_operations_to_make_all_array_elements_equal_to_zero/readme.md new file mode 100644 index 00000000..b9830f42 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2772_apply_operations_to_make_all_array_elements_equal_to_zero/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) + +## 2772\. Apply Operations to Make All Array Elements Equal to Zero + +Medium + +You are given a **0-indexed** integer array `nums` and a positive integer `k`. + +You can apply the following operation on the array **any** number of times: + +* Choose **any** subarray of size `k` from the array and **decrease** all its elements by `1`. + +Return `true` _if you can make all the array elements equal to_ `0`_, or_ `false` _otherwise_. + +A **subarray** is a contiguous non-empty part of an array. + +**Example 1:** + +**Input:** nums = [2,2,3,1,1,0], k = 3 + +**Output:** true + +**Explanation:** + +We can do the following operations: + +- Choose the subarray [2,2,3]. The resulting array will be nums = [**1**,**1**,**2**,1,1,0]. + +- Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,**1**,**0**,**0**,0]. + +- Choose the subarray [1,1,1]. The resulting array will be nums = [**0**,**0**,**0**,0,0,0]. + +**Example 2:** + +**Input:** nums = [1,3,1,1], k = 2 + +**Output:** false + +**Explanation:** It is not possible to make all the array elements equal to 0. + +**Constraints:** + +* 1 <= k <= nums.length <= 105 +* 0 <= nums[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun checkArray(nums: IntArray, k: Int): Boolean { + var cur = 0 + val n = nums.size + for (i in 0 until n) { + if (cur > nums[i]) { + return false + } + nums[i] -= cur + cur += nums[i] + if (i >= k - 1) { + cur -= nums[i - k + 1] + } + } + return cur == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2778_sum_of_squares_of_special_elements/readme.md b/src/main/kotlin/g2701_2800/s2778_sum_of_squares_of_special_elements/readme.md new file mode 100644 index 00000000..ac16d8ca --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2778_sum_of_squares_of_special_elements/readme.md @@ -0,0 +1,55 @@ +[![](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) + +## 2778\. Sum of Squares of Special Elements + +Easy + +You are given a **1-indexed** integer array `nums` of length `n`. + +An element `nums[i]` of `nums` is called **special** if `i` divides `n`, i.e. `n % i == 0`. + +Return _the **sum of the squares** of all **special** elements of_ `nums`. + +**Example 1:** + +**Input:** nums = [1,2,3,4] + +**Output:** 21 + +**Explanation:** + +There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. + +Hence, the sum of the squares of all special elements of nums is nums[1] \* nums[1] + nums[2] \* nums[2] + nums[4] \* nums[4] = 1 \* 1 + 2 \* 2 + 4 \* 4 = 21. + +**Example 2:** + +**Input:** nums = [2,7,1,19,18,3] + +**Output:** 63 + +**Explanation:** + +There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. + +Hence, the sum of the squares of all special elements of nums is nums[1] \* nums[1] + nums[2] \* nums[2] + nums[3] \* nums[3] + nums[6] \* nums[6] = 2 \* 2 + 7 \* 7 + 1 \* 1 + 3 \* 3 = 63. + +**Constraints:** + +* `1 <= nums.length == n <= 50` +* `1 <= nums[i] <= 50` + +## Solution + +```kotlin +class Solution { + fun sumOfSquares(nums: IntArray): Int { + var sum = 0 + for (i in nums.indices) { + if (nums.size % (i + 1) == 0) sum += nums[i] * nums[i] + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2779_maximum_beauty_of_an_array_after_applying_operation/readme.md b/src/main/kotlin/g2701_2800/s2779_maximum_beauty_of_an_array_after_applying_operation/readme.md new file mode 100644 index 00000000..a7757de7 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2779_maximum_beauty_of_an_array_after_applying_operation/readme.md @@ -0,0 +1,76 @@ +[![](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) + +## 2779\. Maximum Beauty of an Array After Applying Operation + +Medium + +You are given a **0-indexed** array `nums` and a **non-negative** integer `k`. + +In one operation, you can do the following: + +* Choose an index `i` that **hasn't been chosen before** from the range `[0, nums.length - 1]`. +* Replace `nums[i]` with any integer from the range `[nums[i] - k, nums[i] + k]`. + +The **beauty** of the array is the length of the longest subsequence consisting of equal elements. + +Return _the **maximum** possible beauty of the array_ `nums` _after applying the operation any number of times._ + +**Note** that you can apply the operation to each index **only once**. + +A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements. + +**Example 1:** + +**Input:** nums = [4,6,1,2], k = 2 + +**Output:** 3 + +**Explanation:** + +In this example, we apply the following operations: + +- Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2]. + +- Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4]. + +After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3). + +It can be proven that 3 is the maximum possible length we can achieve. + +**Example 2:** + +**Input:** nums = [1,1,1,1], k = 10 + +**Output:** 4 + +**Explanation:** + +In this example we don't have to apply any operations. + +The beauty of the array nums is 4 (whole array). + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i], k <= 105 + +## Solution + +```kotlin +class Solution { + fun maximumBeauty(nums: IntArray, k: Int): Int { + nums.sort() + var i = 0 + val n = nums.size + var j = 0 + while (j < n) { + if (nums[j] - nums[i] > k * 2) { + i++ + } + ++j + } + return j - i + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2780_minimum_index_of_a_valid_split/readme.md b/src/main/kotlin/g2701_2800/s2780_minimum_index_of_a_valid_split/readme.md new file mode 100644 index 00000000..37df9b66 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2780_minimum_index_of_a_valid_split/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) + +## 2780\. Minimum Index of a Valid Split + +Medium + +An element `x` of an integer array `arr` of length `m` is **dominant** if `freq(x) * 2 > m`, where `freq(x)` is the number of occurrences of `x` in `arr`. Note that this definition implies that `arr` can have **at most one** dominant element. + +You are given a **0-indexed** integer array `nums` of length `n` with one dominant element. + +You can split `nums` at an index `i` into two arrays `nums[0, ..., i]` and `nums[i + 1, ..., n - 1]`, but the split is only **valid** if: + +* `0 <= i < n - 1` +* `nums[0, ..., i]`, and `nums[i + 1, ..., n - 1]` have the same dominant element. + +Here, `nums[i, ..., j]` denotes the subarray of `nums` starting at index `i` and ending at index `j`, both ends being inclusive. Particularly, if `j < i` then `nums[i, ..., j]` denotes an empty subarray. + +Return _the **minimum** index of a **valid split**_. If no valid split exists, return `-1`. + +**Example 1:** + +**Input:** nums = [1,2,2,2] + +**Output:** 2 + +**Explanation:** + +We can split the array at index 2 to obtain arrays [1,2,2] and [2]. + +In array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 \* 2 > 3. + +In array [2], element 2 is dominant since it occurs once in the array and 1 \* 2 > 1. + +Both [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. + +It can be shown that index 2 is the minimum index of a valid split. + +**Example 2:** + +**Input:** nums = [2,1,3,1,1,1,7,1,2,1] + +**Output:** 4 + +**Explanation:** + +We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1]. + +In array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 \* 2 > 5. + +In array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 \* 2 > 5. + +Both [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split. + +It can be shown that index 4 is the minimum index of a valid split. + +**Example 3:** + +**Input:** nums = [3,3,3,3,7,2,2] + +**Output:** -1 + +**Explanation:** + +It can be shown that there is no valid split. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* `nums` has exactly one dominant element. + +## Solution + +```kotlin +class Solution { + fun minimumIndex(nums: List): Int { + val map = HashMap() + map[0] = 0 + var max = 0 + val m = nums.size + for (n in nums) { + map[n] = map.getOrDefault(n, 0) + 1 + if (map[n]!! > map[max]!!) { + max = n + } + } + var freq = 0 + for (i in 0 until m) { + if (nums[i] == max) { + freq++ + } + if (freq * 2 > i + 1 && (map[max]!! - freq) * 2 > m - i - 1) { + return i + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2781_length_of_the_longest_valid_substring/readme.md b/src/main/kotlin/g2701_2800/s2781_length_of_the_longest_valid_substring/readme.md new file mode 100644 index 00000000..5c9e0517 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2781_length_of_the_longest_valid_substring/readme.md @@ -0,0 +1,76 @@ +[![](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) + +## 2781\. Length of the Longest Valid Substring + +Hard + +You are given a string `word` and an array of strings `forbidden`. + +A string is called **valid** if none of its substrings are present in `forbidden`. + +Return _the length of the **longest valid substring** of the string_ `word`. + +A **substring** is a contiguous sequence of characters in a string, possibly empty. + +**Example 1:** + +**Input:** word = "cbaaaabc", forbidden = ["aaa","cb"] + +**Output:** 4 + +**Explanation:** + +There are 9 valid substrings in word: "c", "b", "a", "ba", "aa", "bc", "baa", "aab", "ab", "abc"and "aabc". The length of the longest valid substring is 4. + +It can be shown that all other substrings contain either "aaa" or "cb" as a substring. + +**Example 2:** + +**Input:** word = "leetcode", forbidden = ["de","le","e"] + +**Output:** 4 + +**Explanation:** + +There are 11 valid substrings in word: "l", "t", "c", "o", "d", "tc", "co", "od", "tco", "cod", and "tcod". The length of the longest valid substring is 4. + +It can be shown that all other substrings contain either "de", "le", or "e" as a substring. + +**Constraints:** + +* 1 <= word.length <= 105 +* `word` consists only of lowercase English letters. +* 1 <= forbidden.length <= 105 +* `1 <= forbidden[i].length <= 10` +* `forbidden[i]` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun longestValidSubstring(word: String, forbidden: List): Int { + val set = HashSet() + for (s in forbidden) { + set.add(s) + } + val n = word.length + var ans = 0 + var i = 0 + var j = 0 + while (j < n) { + var k = j + while (k > j - 10 && k >= i) { + if (set.contains(word.substring(k, j + 1))) { + i = k + 1 + break + } + k-- + } + ans = Math.max(j - i + 1, ans) + j++ + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2784_check_if_array_is_good/readme.md b/src/main/kotlin/g2701_2800/s2784_check_if_array_is_good/readme.md new file mode 100644 index 00000000..f52ebb94 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2784_check_if_array_is_good/readme.md @@ -0,0 +1,82 @@ +[![](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) + +## 2784\. Check if Array is Good + +Easy + +You are given an integer array `nums`. We consider an array **good** if it is a permutation of an array `base[n]`. + +`base[n] = [1, 2, ..., n - 1, n, n]` (in other words, it is an array of length `n + 1` which contains `1` to `n - 1` exactly once, plus two occurrences of `n`). For example, `base[1] = [1, 1]` and `base[3] = [1, 2, 3, 3]`. + +Return `true` _if the given array is good, otherwise return_ `false`. + +**Note:** A permutation of integers represents an arrangement of these numbers. + +**Example 1:** + +**Input:** nums = [2, 1, 3] + +**Output:** false + +**Explanation:** Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false. + +**Example 2:** + +**Input:** nums = [1, 3, 3, 2] + +**Output:** true + +**Explanation:** Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true. + +**Example 3:** + +**Input:** nums = [1, 1] + +**Output:** true + +**Explanation:** Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true. + +**Example 4:** + +**Input:** nums = [3, 4, 4, 1, 2, 1] + +**Output:** false + +**Explanation:** Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= num[i] <= 200` + +## Solution + +```kotlin +class Solution { + fun isGood(nums: IntArray): Boolean { + var max = Int.MIN_VALUE + var sum = 0 + for (i in nums) { + if (i > max) { + max = i + } + sum += i + } + if (max != nums.size - 1) { + return false + } + val newSum = max * (max + 1) / 2 + max + if (sum != newSum) { + return false + } + var count = 0 + for (i in nums) { + if (i == max) { + count++ + } + } + return count == 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2785_sort_vowels_in_a_string/readme.md b/src/main/kotlin/g2701_2800/s2785_sort_vowels_in_a_string/readme.md new file mode 100644 index 00000000..57541b0c --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2785_sort_vowels_in_a_string/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) + +## 2785\. Sort Vowels in a String + +Medium + +Given a **0-indexed** string `s`, **permute** `s` to get a new string `t` such that: + +* All consonants remain in their original places. More formally, if there is an index `i` with `0 <= i < s.length` such that `s[i]` is a consonant, then `t[i] = s[i]`. +* The vowels must be sorted in the **nondecreasing** order of their **ASCII** values. More formally, for pairs of indices `i`, `j` with `0 <= i < j < s.length` such that `s[i]` and `s[j]` are vowels, then `t[i]` must not have a higher ASCII value than `t[j]`. + +Return _the resulting string_. + +The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels. + +**Example 1:** + +**Input:** s = "lEetcOde" + +**Output:** "lEOtcede" + +**Explanation:** 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places. + +**Example 2:** + +**Input:** s = "lYmpH" + +**Output:** "lYmpH" + +**Explanation:** There are no vowels in s (all characters in s are consonants), so we return "lYmpH". + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists only of letters of the English alphabet in **uppercase and lowercase**. + +## Solution + +```kotlin +class Solution { + fun sortVowels(s: String): String { + val vowelCount = IntArray(11) + val countIndexMap = IntArray(128) + val result = s.toCharArray() + val charMap = "AEIOUaeiou".toCharArray() + run { + var i = 0 + while (i < charMap.size) { + countIndexMap[charMap[i].code] = ++i + } + } + for (c in result) vowelCount[countIndexMap[c.code]]++ + var j = 1 + var i = 0 + while (j < vowelCount.size) { + if (vowelCount[j] > 0) while (i < result.size) { + if (countIndexMap[result[i++].code] == 0) continue + vowelCount[j]-- + result[i - 1] = charMap[j - 1] + break + } else j++ + } + return String(result) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2786_visit_array_positions_to_maximize_score/readme.md b/src/main/kotlin/g2701_2800/s2786_visit_array_positions_to_maximize_score/readme.md new file mode 100644 index 00000000..ba6763db --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2786_visit_array_positions_to_maximize_score/readme.md @@ -0,0 +1,68 @@ +[![](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) + +## 2786\. Visit Array Positions to Maximize Score + +Medium + +You are given a **0-indexed** integer array `nums` and a positive integer `x`. + +You are **initially** at position `0` in the array and you can visit other positions according to the following rules: + +* If you are currently in position `i`, then you can move to **any** position `j` such that `i < j`. +* For each position `i` that you visit, you get a score of `nums[i]`. +* If you move from a position `i` to a position `j` and the **parities** of `nums[i]` and `nums[j]` differ, then you lose a score of `x`. + +Return _the **maximum** total score you can get_. + +**Note** that initially you have `nums[0]` points. + +**Example 1:** + +**Input:** nums = [2,3,6,1,9,2], x = 5 + +**Output:** 13 + +**Explanation:** + +We can visit the following positions in the array: 0 -> 2 -> 3 -> 4. + +The corresponding values are 2, 6, 1 and 9. Since the integers 6 and 1 have different parities, the move 2 -> 3 will make you lose a score of x = 5. + +The total score will be: 2 + 6 + 1 + 9 - 5 = 13. + +**Example 2:** + +**Input:** nums = [2,4,6,8], x = 3 + +**Output:** 20 + +**Explanation:** + +All the integers in the array have the same parities, so we can visit all of them without losing any score. + +The total score is: 2 + 4 + 6 + 8 = 20. + +**Constraints:** + +* 2 <= nums.length <= 105 +* 1 <= nums[i], x <= 106 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maxScore(nums: IntArray, x: Int): Long { + val dp = longArrayOf(-x.toLong(), -x.toLong()) + dp[nums[0] and 1] = nums[0].toLong() + for (i in 1 until nums.size) { + val toggle = dp[nums[i] and 1 xor 1] - x + val nottoggle = dp[nums[i] and 1] + dp[nums[i] and 1] = (max(toggle.toDouble(), nottoggle.toDouble()) + nums[i]).toLong() + } + return max(dp[0].toDouble(), dp[1].toDouble()).toLong() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2787_ways_to_express_an_integer_as_sum_of_powers/readme.md b/src/main/kotlin/g2701_2800/s2787_ways_to_express_an_integer_as_sum_of_powers/readme.md new file mode 100644 index 00000000..758b6797 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2787_ways_to_express_an_integer_as_sum_of_powers/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) + +## 2787\. Ways to Express an Integer as Sum of Powers + +Medium + +Given two **positive** integers `n` and `x`. + +Return _the number of ways_ `n` _can be expressed as the sum of the_ xth _power of **unique** positive integers, in other words, the number of sets of unique integers_ [n1, n2, ..., nk] _where_ n = n1x + n2x + ... + nkx_._ + +Since the result can be very large, return it modulo 109 + 7. + +For example, if `n = 160` and `x = 3`, one way to express `n` is n = 23 + 33 + 53. + +**Example 1:** + +**Input:** n = 10, x = 2 + +**Output:** 1 + +**Explanation:** + +We can express n as the following: n = 32 + 12 = 10. + +It can be shown that it is the only way to express 10 as the sum of the 2nd power of unique integers. + +**Example 2:** + +**Input:** n = 4, x = 1 + +**Output:** 2 + +**Explanation:** + +We can express n in the following ways: + +- n = 41 = 4. + +- n = 31 + 11 = 4. + +**Constraints:** + +* `1 <= n <= 300` +* `1 <= x <= 5` + +## Solution + +```kotlin +class Solution { + fun numberOfWays(n: Int, x: Int): Int { + val dp = IntArray(301) + val mod = 1000000007 + var v: Int + dp[0] = 1 + var a = 1 + while ((Math.pow(a.toDouble(), x.toDouble())).also { v = it.toInt() } <= n) { + for (i in n downTo v) { + dp[i] = (dp[i] + dp[i - v]) % mod + } + a++ + } + return dp[n] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2788_split_strings_by_separator/readme.md b/src/main/kotlin/g2701_2800/s2788_split_strings_by_separator/readme.md new file mode 100644 index 00000000..836275b7 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2788_split_strings_by_separator/readme.md @@ -0,0 +1,90 @@ +[![](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) + +## 2788\. Split Strings by Separator + +Easy + +Given an array of strings `words` and a character `separator`, **split** each string in `words` by `separator`. + +Return _an array of strings containing the new strings formed after the splits, **excluding empty strings**._ + +**Notes** + +* `separator` is used to determine where the split should occur, but it is not included as part of the resulting strings. +* A split may result in more than two strings. +* The resulting strings must maintain the same order as they were initially given. + +**Example 1:** + +**Input:** words = ["one.two.three","four.five","six"], separator = "." + +**Output:** ["one","two","three","four","five","six"] + +**Explanation:** + +In this example we split as follows: "one.two.three" splits into + +"one", "two", "three" "four.five" splits into + +"four", "five" "six" splits into "six" + +Hence, the resulting array is ["one","two","three","four","five","six"]. + +**Example 2:** + +**Input:** words = ["$easy$","$problem$"], separator = "$" + +**Output:** ["easy","problem"] + +**Explanation:** + +In this example we split as follows: + +"$easy$" splits into "easy" (excluding empty strings) + +"$problem$" splits into "problem" (excluding empty strings) + +Hence, the resulting array is ["easy","problem"]. + +**Example 3:** + +**Input:** words = ["\|\|\|"], separator = "\|" + +**Output:** [] + +**Explanation:** + +In this example the resulting split of "\|\|\|" will contain only empty strings, so we return an empty array []. + +**Constraints:** + +* `1 <= words.length <= 100` +* `1 <= words[i].length <= 20` +* characters in `words[i]` are either lowercase English letters or characters from the string `".,|$#@"` (excluding the quotes) +* `separator` is a character from the string `".,|$#@"` (excluding the quotes) + +## Solution + +```kotlin +class Solution { + fun splitWordsBySeparator(words: List, separator: Char): List { + val list: MutableList = ArrayList() + for (str in words) { + var si = 0 + for (i in str.indices) { + if (str[i] == separator) { + if (i > si) { + list.add(str.substring(si, i)) + } + si = i + 1 + } + } + if (si != str.length) { + list.add(str.substring(si, str.length)) + } + } + return list + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2789_largest_element_in_an_array_after_merge_operations/readme.md b/src/main/kotlin/g2701_2800/s2789_largest_element_in_an_array_after_merge_operations/readme.md new file mode 100644 index 00000000..33ad1e38 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2789_largest_element_in_an_array_after_merge_operations/readme.md @@ -0,0 +1,71 @@ +[![](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) + +## 2789\. Largest Element in an Array after Merge Operations + +Medium + +You are given a **0-indexed** array `nums` consisting of positive integers. + +You can do the following operation on the array **any** number of times: + +* Choose an integer `i` such that `0 <= i < nums.length - 1` and `nums[i] <= nums[i + 1]`. Replace the element `nums[i + 1]` with `nums[i] + nums[i + 1]` and delete the element `nums[i]` from the array. + +Return _the value of the **largest** element that you can possibly obtain in the final array._ + +**Example 1:** + +**Input:** nums = [2,3,7,9,3] + +**Output:** 21 + +**Explanation:** + +We can apply the following operations on the array: + +- Choose i = 0. The resulting array will be nums = [5,7,9,3]. + +- Choose i = 1. The resulting array will be nums = [5,16,3]. + +- Choose i = 0. The resulting array will be nums = [21,3]. + +The largest element in the final array is 21. It can be shown that we cannot obtain a larger element. + +**Example 2:** + +**Input:** nums = [5,3,3] + +**Output:** 11 + +**Explanation:** + +We can do the following operations on the array: + +- Choose i = 1. The resulting array will be nums = [5,6]. + +- Choose i = 0. The resulting array will be nums = [11]. + +There is only one element in the final array, which is 11. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun maxArrayValue(nums: IntArray): Long { + var ans = nums[nums.size - 1].toLong() + for (i in nums.size - 1 downTo 1) { + if (ans >= nums[i - 1]) { + ans += nums[i - 1].toLong() + } else { + ans = nums[i - 1].toLong() + } + } + return ans + } +} +``` \ No newline at end of file