diff --git a/src/main/java/g3401_3500/s3407_substring_matching_pattern/Solution.java b/src/main/java/g3401_3500/s3407_substring_matching_pattern/Solution.java new file mode 100644 index 000000000..acd8024e6 --- /dev/null +++ b/src/main/java/g3401_3500/s3407_substring_matching_pattern/Solution.java @@ -0,0 +1,40 @@ +package g3401_3500.s3407_substring_matching_pattern; + +// #Easy #String #String_Matching #2025_01_06_Time_1_(100.00%)_Space_42.63_(100.00%) + +public class Solution { + public boolean hasMatch(String s, String p) { + int index = -1; + for (int i = 0; i < p.length(); i++) { + if (p.charAt(i) == '*') { + index = i; + break; + } + } + int num1 = fun(s, p.substring(0, index)); + if (num1 == -1) { + return false; + } + int num2 = fun(s.substring(num1), p.substring(index + 1)); + return num2 != -1; + } + + private int fun(String s, String k) { + int n = s.length(); + int m = k.length(); + int j = 0; + for (int i = 0; i <= n - m; i++) { + for (j = 0; j < m; j++) { + char ch1 = s.charAt(j + i); + char ch2 = k.charAt(j); + if (ch1 != ch2) { + break; + } + } + if (j == m) { + return i + j; + } + } + return -1; + } +} diff --git a/src/main/java/g3401_3500/s3407_substring_matching_pattern/readme.md b/src/main/java/g3401_3500/s3407_substring_matching_pattern/readme.md new file mode 100644 index 000000000..6d00108c9 --- /dev/null +++ b/src/main/java/g3401_3500/s3407_substring_matching_pattern/readme.md @@ -0,0 +1,48 @@ +3407\. Substring Matching Pattern + +Easy + +You are given a string `s` and a pattern string `p`, where `p` contains **exactly one** `'*'` character. + +The `'*'` in `p` can be replaced with any sequence of zero or more characters. + +Return `true` if `p` can be made a substring of `s`, and `false` otherwise. + +A **substring** is a contiguous **non-empty** sequence of characters within a string. + +**Example 1:** + +**Input:** s = "leetcode", p = "ee\*e" + +**Output:** true + +**Explanation:** + +By replacing the `'*'` with `"tcod"`, the substring `"eetcode"` matches the pattern. + +**Example 2:** + +**Input:** s = "car", p = "c\*v" + +**Output:** false + +**Explanation:** + +There is no substring matching the pattern. + +**Example 3:** + +**Input:** s = "luck", p = "u\*" + +**Output:** true + +**Explanation:** + +The substrings `"u"`, `"uc"`, and `"uck"` match the pattern. + +**Constraints:** + +* `1 <= s.length <= 50` +* `1 <= p.length <= 50` +* `s` contains only lowercase English letters. +* `p` contains only lowercase English letters and exactly one `'*'` \ No newline at end of file diff --git a/src/main/java/g3401_3500/s3408_design_task_manager/TaskManager.java b/src/main/java/g3401_3500/s3408_design_task_manager/TaskManager.java new file mode 100644 index 000000000..491a28657 --- /dev/null +++ b/src/main/java/g3401_3500/s3408_design_task_manager/TaskManager.java @@ -0,0 +1,63 @@ +package g3401_3500.s3408_design_task_manager; + +// #Medium #Hash_Table #Design #Heap_Priority_Queue #Ordered_Set +// #2025_01_06_Time_349_(100.00%)_Space_152.40_(100.00%) + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; + +public class TaskManager { + + private TreeSet tasks; + private Map taskMap; + + public TaskManager(List> tasks) { + this.tasks = new TreeSet<>((a, b) -> b[2] == a[2] ? b[1] - a[1] : b[2] - a[2]); + this.taskMap = new HashMap<>(); + for (List task : tasks) { + int[] t = new int[] {task.get(0), task.get(1), task.get(2)}; + this.tasks.add(t); + this.taskMap.put(task.get(1), t); + } + } + + public void add(int userId, int taskId, int priority) { + int[] task = new int[] {userId, taskId, priority}; + this.tasks.add(task); + this.taskMap.put(taskId, task); + } + + public void edit(int taskId, int newPriority) { + int[] task = taskMap.get(taskId); + tasks.remove(task); + taskMap.remove(taskId); + int[] newTask = new int[] {task[0], task[1], newPriority}; + tasks.add(newTask); + taskMap.put(taskId, newTask); + } + + public void rmv(int taskId) { + this.tasks.remove(this.taskMap.get(taskId)); + this.taskMap.remove(taskId); + } + + public int execTop() { + if (this.tasks.isEmpty()) { + return -1; + } + int[] task = this.tasks.pollFirst(); + this.taskMap.remove(task[1]); + return task[0]; + } +} + +/* + * Your TaskManager object will be instantiated and called as such: + * TaskManager obj = new TaskManager(tasks); + * obj.add(userId,taskId,priority); + * obj.edit(taskId,newPriority); + * obj.rmv(taskId); + * int param_4 = obj.execTop(); + */ diff --git a/src/main/java/g3401_3500/s3408_design_task_manager/readme.md b/src/main/java/g3401_3500/s3408_design_task_manager/readme.md new file mode 100644 index 000000000..9c38851f2 --- /dev/null +++ b/src/main/java/g3401_3500/s3408_design_task_manager/readme.md @@ -0,0 +1,48 @@ +3408\. Design Task Manager + +Medium + +There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks. + +Implement the `TaskManager` class: + +* `TaskManager(vector>& tasks)` initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form `[userId, taskId, priority]`, which adds a task to the specified user with the given priority. + +* `void add(int userId, int taskId, int priority)` adds a task with the specified `taskId` and `priority` to the user with `userId`. It is **guaranteed** that `taskId` does not _exist_ in the system. + +* `void edit(int taskId, int newPriority)` updates the priority of the existing `taskId` to `newPriority`. It is **guaranteed** that `taskId` _exists_ in the system. + +* `void rmv(int taskId)` removes the task identified by `taskId` from the system. It is **guaranteed** that `taskId` _exists_ in the system. + +* `int execTop()` executes the task with the **highest** priority across all users. If there are multiple tasks with the same **highest** priority, execute the one with the highest `taskId`. After executing, the `taskId` is **removed** from the system. Return the `userId` associated with the executed task. If no tasks are available, return -1. + + +**Note** that a user may be assigned multiple tasks. + +**Example 1:** + +**Input:** + ["TaskManager", "add", "edit", "execTop", "rmv", "add", "execTop"] + [[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []] + +**Output:** + [null, null, null, 3, null, null, 5] + +**Explanation** + +TaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3. + taskManager.add(4, 104, 5); // Adds task 104 with priority 5 for User 4. + taskManager.edit(102, 8); // Updates priority of task 102 to 8. + taskManager.execTop(); // return 3. Executes task 103 for User 3. + taskManager.rmv(101); // Removes task 101 from the system. + taskManager.add(5, 105, 15); // Adds task 105 with priority 15 for User 5. + taskManager.execTop(); // return 5. Executes task 105 for User 5. + +**Constraints:** + +* 1 <= tasks.length <= 105 +* 0 <= userId <= 105 +* 0 <= taskId <= 105 +* 0 <= priority <= 109 +* 0 <= newPriority <= 109 +* At most 2 * 105 calls will be made in **total** to `add`, `edit`, `rmv`, and `execTop` methods. \ No newline at end of file diff --git a/src/main/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/Solution.java b/src/main/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/Solution.java new file mode 100644 index 000000000..603b8afdf --- /dev/null +++ b/src/main/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/Solution.java @@ -0,0 +1,33 @@ +package g3401_3500.s3409_longest_subsequence_with_decreasing_adjacent_difference; + +// #Medium #Array #Dynamic_Programming #2025_01_07_Time_68_(99.55%)_Space_45.74_(78.73%) + +public class Solution { + public int longestSubsequence(int[] nums) { + int max = 0; + for (int n : nums) { + max = Math.max(n, max); + } + max += 1; + int[][] dp = new int[max][max]; + for (int i : nums) { + int v = 1; + for (int diff = max - 1; diff >= 0; diff--) { + if (i + diff < max) { + v = Math.max(v, dp[i + diff][diff] + 1); + } + if (i - diff >= 0) { + v = Math.max(v, dp[i - diff][diff] + 1); + } + dp[i][diff] = v; + } + } + int res = 0; + for (int[] i : dp) { + for (int j : i) { + res = Math.max(res, j); + } + } + return res; + } +} diff --git a/src/main/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/readme.md b/src/main/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/readme.md new file mode 100644 index 000000000..23b570516 --- /dev/null +++ b/src/main/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/readme.md @@ -0,0 +1,46 @@ +3409\. Longest Subsequence With Decreasing Adjacent Difference + +Medium + +You are given an array of integers `nums`. + +Your task is to find the length of the **longest subsequence** `seq` of `nums`, such that the **absolute differences** between _consecutive_ elements form a **non-increasing sequence** of integers. In other words, for a subsequence seq0, seq1, seq2, ..., seqm of `nums`, |seq1 - seq0| >= |seq2 - seq1| >= ... >= |seqm - seqm - 1|. + +Return the length of such a subsequence. + +A **subsequence** is an **non-empty** 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 = [16,6,3] + +**Output:** 3 + +**Explanation:** + +The longest subsequence is `[16, 6, 3]` with the absolute adjacent differences `[10, 3]`. + +**Example 2:** + +**Input:** nums = [6,5,3,4,2,1] + +**Output:** 4 + +**Explanation:** + +The longest subsequence is `[6, 4, 2, 1]` with the absolute adjacent differences `[2, 2, 1]`. + +**Example 3:** + +**Input:** nums = [10,20,10,19,10,20] + +**Output:** 5 + +**Explanation:** + +The longest subsequence is `[10, 20, 10, 19, 10]` with the absolute adjacent differences `[10, 10, 9, 9]`. + +**Constraints:** + +* 2 <= nums.length <= 104 +* `1 <= nums[i] <= 300` \ No newline at end of file diff --git a/src/main/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/Solution.java b/src/main/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/Solution.java new file mode 100644 index 000000000..d16511fba --- /dev/null +++ b/src/main/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/Solution.java @@ -0,0 +1,33 @@ +package g3401_3500.s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element; + +// #Hard #Array #Dynamic_Programming #Segment_Tree #2025_01_07_Time_51_(97.96%)_Space_57.22_(85.71%) + +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public long maxSubarraySum(int[] nums) { + Map prefixMap = new HashMap<>(); + long result = nums[0]; + long prefixSum = 0; + long minPrefix = 0; + prefixMap.put(0L, 0L); + for (int num : nums) { + prefixSum += num; + result = Math.max(result, prefixSum - minPrefix); + if (num < 0) { + if (prefixMap.containsKey((long) num)) { + prefixMap.put( + (long) num, + Math.min(prefixMap.get((long) num), prefixMap.get(0L)) + num); + } else { + prefixMap.put((long) num, prefixMap.get(0L) + num); + } + minPrefix = Math.min(minPrefix, prefixMap.get((long) num)); + } + prefixMap.put(0L, Math.min(prefixMap.get(0L), prefixSum)); + minPrefix = Math.min(minPrefix, prefixMap.get(0L)); + } + return result; + } +} diff --git a/src/main/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/readme.md b/src/main/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/readme.md new file mode 100644 index 000000000..0d05dd232 --- /dev/null +++ b/src/main/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/readme.md @@ -0,0 +1,47 @@ +3410\. Maximize Subarray Sum After Removing All Occurrences of One Element + +Hard + +You are given an integer array `nums`. + +You can do the following operation on the array **at most** once: + +* Choose **any** integer `x` such that `nums` remains **non-empty** on removing all occurrences of `x`. +* Remove **all** occurrences of `x` from the array. + +Return the **maximum** subarray sum across **all** possible resulting arrays. + +A **subarray** is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [-3,2,-2,-1,3,-2,3] + +**Output:** 7 + +**Explanation:** + +We can have the following arrays after at most one operation: + +* The original array is nums = [-3, 2, -2, -1, **3, -2, 3**]. The maximum subarray sum is `3 + (-2) + 3 = 4`. +* Deleting all occurences of `x = -3` results in nums = [2, -2, -1, **3, -2, 3**]. The maximum subarray sum is `3 + (-2) + 3 = 4`. +* Deleting all occurences of `x = -2` results in nums = [-3, **2, -1, 3, 3**]. The maximum subarray sum is `2 + (-1) + 3 + 3 = 7`. +* Deleting all occurences of `x = -1` results in nums = [-3, 2, -2, **3, -2, 3**]. The maximum subarray sum is `3 + (-2) + 3 = 4`. +* Deleting all occurences of `x = 3` results in nums = [-3, **2**, -2, -1, -2]. The maximum subarray sum is 2. + +The output is `max(4, 4, 7, 4, 2) = 7`. + +**Example 2:** + +**Input:** nums = [1,2,3,4] + +**Output:** 10 + +**Explanation:** + +It is optimal to not perform any operations. + +**Constraints:** + +* 1 <= nums.length <= 105 +* -106 <= nums[i] <= 106 \ No newline at end of file diff --git a/src/main/java/g3401_3500/s3411_maximum_subarray_with_equal_products/Solution.java b/src/main/java/g3401_3500/s3411_maximum_subarray_with_equal_products/Solution.java new file mode 100644 index 000000000..8a914f48a --- /dev/null +++ b/src/main/java/g3401_3500/s3411_maximum_subarray_with_equal_products/Solution.java @@ -0,0 +1,33 @@ +package g3401_3500.s3411_maximum_subarray_with_equal_products; + +// #Easy #Array #Math #Sliding_Window #Enumeration #Number_Theory +// #2025_01_07_Time_3_(91.26%)_Space_42.68_(64.20%) + +public class Solution { + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + + private int lcm(int a, int b) { + return (a / gcd(a, b)) * b; + } + + public int maxLength(int[] nums) { + int n = nums.length; + int maxL = 0; + for (int i = 0; i < n; i++) { + int currGCD = nums[i]; + int currLCM = nums[i]; + int currPro = nums[i]; + for (int j = i + 1; j < n; j++) { + currPro *= nums[j]; + currGCD = gcd(currGCD, nums[j]); + currLCM = lcm(currLCM, nums[j]); + if (currPro == currLCM * currGCD) { + maxL = Math.max(maxL, j - i + 1); + } + } + } + return maxL; + } +} diff --git a/src/main/java/g3401_3500/s3411_maximum_subarray_with_equal_products/readme.md b/src/main/java/g3401_3500/s3411_maximum_subarray_with_equal_products/readme.md new file mode 100644 index 000000000..33447a1d3 --- /dev/null +++ b/src/main/java/g3401_3500/s3411_maximum_subarray_with_equal_products/readme.md @@ -0,0 +1,50 @@ +3411\. Maximum Subarray With Equal Products + +Easy + +You are given an array of **positive** integers `nums`. + +An array `arr` is called **product equivalent** if `prod(arr) == lcm(arr) * gcd(arr)`, where: + +* `prod(arr)` is the product of all elements of `arr`. +* `gcd(arr)` is the GCD of all elements of `arr`. +* `lcm(arr)` is the LCM of all elements of `arr`. + +Return the length of the **longest** **product equivalent** subarray of `nums`. + +A **subarray** is a contiguous **non-empty** sequence of elements within an array. + +The term `gcd(a, b)` denotes the **greatest common divisor** of `a` and `b`. + +The term `lcm(a, b)` denotes the **least common multiple** of `a` and `b`. + +**Example 1:** + +**Input:** nums = [1,2,1,2,1,1,1] + +**Output:** 5 + +**Explanation:** + +The longest product equivalent subarray is `[1, 2, 1, 1, 1]`, where `prod([1, 2, 1, 1, 1]) = 2`, `gcd([1, 2, 1, 1, 1]) = 1`, and `lcm([1, 2, 1, 1, 1]) = 2`. + +**Example 2:** + +**Input:** nums = [2,3,4,5,6] + +**Output:** 3 + +**Explanation:** + +The longest product equivalent subarray is `[3, 4, 5].` + +**Example 3:** + +**Input:** nums = [1,2,3,1,4,5,1] + +**Output:** 5 + +**Constraints:** + +* `2 <= nums.length <= 100` +* `1 <= nums[i] <= 10` \ No newline at end of file diff --git a/src/main/java/g3401_3500/s3412_find_mirror_score_of_a_string/Solution.java b/src/main/java/g3401_3500/s3412_find_mirror_score_of_a_string/Solution.java new file mode 100644 index 000000000..76dd19307 --- /dev/null +++ b/src/main/java/g3401_3500/s3412_find_mirror_score_of_a_string/Solution.java @@ -0,0 +1,27 @@ +package g3401_3500.s3412_find_mirror_score_of_a_string; + +// #Medium #String #Hash_Table #Stack #Simulation #2025_01_07_Time_12_(99.54%)_Space_45.78_(74.26%) + +import java.util.ArrayList; + +@SuppressWarnings("unchecked") +public class Solution { + public long calculateScore(String s) { + int n = s.length(); + ArrayList[] st = new ArrayList[26]; + long r = 0; + for (int i = 0; i < 26; i++) { + st[i] = new ArrayList<>(); + } + for (int i = 0; i < n; i++) { + int mc = 'z' - (s.charAt(i) - 'a'); + int p = mc - 'a'; + if (!st[p].isEmpty()) { + r += i - st[p].remove(st[p].size() - 1); + } else { + st[s.charAt(i) - 'a'].add(i); + } + } + return r; + } +} diff --git a/src/main/java/g3401_3500/s3412_find_mirror_score_of_a_string/readme.md b/src/main/java/g3401_3500/s3412_find_mirror_score_of_a_string/readme.md new file mode 100644 index 000000000..a1e0480d6 --- /dev/null +++ b/src/main/java/g3401_3500/s3412_find_mirror_score_of_a_string/readme.md @@ -0,0 +1,46 @@ +3412\. Find Mirror Score of a String + +Medium + +You are given a string `s`. + +We define the **mirror** of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of `'a'` is `'z'`, and the mirror of `'y'` is `'b'`. + +Initially, all characters in the string `s` are **unmarked**. + +You start with a score of 0, and you perform the following process on the string `s`: + +* Iterate through the string from left to right. +* At each index `i`, find the closest **unmarked** index `j` such that `j < i` and `s[j]` is the mirror of `s[i]`. Then, **mark** both indices `i` and `j`, and add the value `i - j` to the total score. +* If no such index `j` exists for the index `i`, move on to the next index without making any changes. + +Return the total score at the end of the process. + +**Example 1:** + +**Input:** s = "aczzx" + +**Output:** 5 + +**Explanation:** + +* `i = 0`. There is no index `j` that satisfies the conditions, so we skip. +* `i = 1`. There is no index `j` that satisfies the conditions, so we skip. +* `i = 2`. The closest index `j` that satisfies the conditions is `j = 0`, so we mark both indices 0 and 2, and then add `2 - 0 = 2` to the score. +* `i = 3`. There is no index `j` that satisfies the conditions, so we skip. +* `i = 4`. The closest index `j` that satisfies the conditions is `j = 1`, so we mark both indices 1 and 4, and then add `4 - 1 = 3` to the score. + +**Example 2:** + +**Input:** s = "abcdef" + +**Output:** 0 + +**Explanation:** + +For each index `i`, there is no index `j` that satisfies the conditions. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists only of lowercase English letters. \ No newline at end of file diff --git a/src/main/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/Solution.java b/src/main/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/Solution.java new file mode 100644 index 000000000..e66f13151 --- /dev/null +++ b/src/main/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/Solution.java @@ -0,0 +1,39 @@ +package g3401_3500.s3413_maximum_coins_from_k_consecutive_bags; + +// #Medium #Array #Sorting #Greedy #Binary_Search #Prefix_Sum #Sliding_Window +// #2025_01_07_Time_82_(92.23%)_Space_134.12_(21.36%) + +import java.util.Arrays; + +public class Solution { + public long maximumCoins(int[][] coins, int k) { + Arrays.sort(coins, (a, b) -> a[0] - b[0]); + int n = coins.length; + long res = 0; + long cur = 0; + int j = 0; + for (int[] ints : coins) { + while (j < n && coins[j][1] <= ints[0] + k - 1) { + cur += (long) (coins[j][1] - coins[j][0] + 1) * coins[j][2]; + j++; + } + if (j < n) { + long part = (long) Math.max(0, ints[0] + k - 1 - coins[j][0] + 1) * coins[j][2]; + res = Math.max(res, cur + part); + } + cur -= (long) (ints[1] - ints[0] + 1) * ints[2]; + } + cur = 0; + j = 0; + for (int[] coin : coins) { + cur += (long) (coin[1] - coin[0] + 1) * coin[2]; + while (coins[j][1] < coin[1] - k + 1) { + cur -= (long) (coins[j][1] - coins[j][0] + 1) * coins[j][2]; + j++; + } + long part = (long) Math.max(0, coin[1] - k - coins[j][0] + 1) * coins[j][2]; + res = Math.max(res, cur - part); + } + return res; + } +} diff --git a/src/main/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/readme.md b/src/main/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/readme.md new file mode 100644 index 000000000..43eacb690 --- /dev/null +++ b/src/main/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/readme.md @@ -0,0 +1,42 @@ +3413\. Maximum Coins From K Consecutive Bags + +Medium + +There are an infinite amount of bags on a number line, one bag for each coordinate. Some of these bags contain coins. + +You are given a 2D array `coins`, where coins[i] = [li, ri, ci] denotes that every bag from li to ri contains ci coins. + +The segments that `coins` contain are non-overlapping. + +You are also given an integer `k`. + +Return the **maximum** amount of coins you can obtain by collecting `k` consecutive bags. + +**Example 1:** + +**Input:** coins = [[8,10,1],[1,3,2],[5,6,4]], k = 4 + +**Output:** 10 + +**Explanation:** + +Selecting bags at positions `[3, 4, 5, 6]` gives the maximum number of coins: `2 + 0 + 4 + 4 = 10`. + +**Example 2:** + +**Input:** coins = [[1,10,3]], k = 2 + +**Output:** 6 + +**Explanation:** + +Selecting bags at positions `[1, 2]` gives the maximum number of coins: `3 + 3 = 6`. + +**Constraints:** + +* 1 <= coins.length <= 105 +* 1 <= k <= 109 +* coins[i] == [li, ri, ci] +* 1 <= li <= ri <= 109 +* 1 <= ci <= 1000 +* The given segments are non-overlapping. \ No newline at end of file diff --git a/src/main/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/Solution.java b/src/main/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/Solution.java new file mode 100644 index 000000000..b200aaa89 --- /dev/null +++ b/src/main/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/Solution.java @@ -0,0 +1,75 @@ +package g3401_3500.s3414_maximum_score_of_non_overlapping_intervals; + +// #Hard #Array #Dynamic_Programming #Sorting #Binary_Search +// #2025_01_08_Time_64_(95.65%)_Space_74.80_(98.26%) + +import java.util.Arrays; +import java.util.List; + +public class Solution { + public int[] maximumWeight(List> intervals) { + final int n = intervals.size(); + final int[][] ns = new int[n][]; + int p = 0; + for (List li : intervals) { + ns[p] = new int[] {li.get(0), li.get(1), li.get(2), p}; + p++; + } + int[][] dp1 = new int[n][0]; + long[] dp = new long[n]; + Arrays.sort(ns, (a, b) -> a[0] - b[0]); + for (int k = 0; k < 4; ++k) { + int[][] dp3 = new int[n][]; + long[] dp2 = new long[n]; + dp3[n - 1] = new int[] {ns[n - 1][3]}; + dp2[n - 1] = ns[n - 1][2]; + for (int i = n - 2; i >= 0; --i) { + int l = i + 1; + int r = n - 1; + while (l <= r) { + final int mid = (l + r) >> 1; + if (ns[mid][0] > ns[i][1]) { + r = mid - 1; + } else { + l = mid + 1; + } + } + dp2[i] = ns[i][2] + (l < n ? dp[l] : 0); + if (i + 1 < n && dp2[i + 1] > dp2[i]) { + dp2[i] = dp2[i + 1]; + dp3[i] = dp3[i + 1]; + } else { + if (l < n) { + dp3[i] = new int[dp1[l].length + 1]; + dp3[i][0] = ns[i][3]; + for (int j = 0; j < dp1[l].length; ++j) { + dp3[i][j + 1] = dp1[l][j]; + } + Arrays.sort(dp3[i]); + } else { + dp3[i] = new int[] {ns[i][3]}; + } + if (i + 1 < n && dp2[i + 1] == dp2[i] && check(dp3[i], dp3[i + 1]) > 0) { + dp3[i] = dp3[i + 1]; + } + } + } + dp = dp2; + dp1 = dp3; + } + return dp1[0]; + } + + private int check(final int[] ns1, final int[] ns2) { + int i = 0; + while (i < ns1.length && i < ns2.length) { + if (ns1[i] < ns2[i]) { + return -1; + } else if (ns1[i] > ns2[i]) { + return 1; + } + i++; + } + return 0; + } +} diff --git a/src/main/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/readme.md b/src/main/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/readme.md new file mode 100644 index 000000000..6dbd6d388 --- /dev/null +++ b/src/main/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/readme.md @@ -0,0 +1,40 @@ +3414\. Maximum Score of Non-overlapping Intervals + +Hard + +You are given a 2D integer array `intervals`, where intervals[i] = [li, ri, weighti]. Interval `i` starts at position li and ends at ri, and has a weight of weighti. You can choose _up to_ 4 **non-overlapping** intervals. The **score** of the chosen intervals is defined as the total sum of their weights. + +Return the **lexicographically smallest** array of at most 4 indices from `intervals` with **maximum** score, representing your choice of non-overlapping intervals. + +Two intervals are said to be **non-overlapping** if they do not share any points. In particular, intervals sharing a left or right boundary are considered overlapping. + +An array `a` is **lexicographically smaller** than an array `b` if in the first position where `a` and `b` differ, array `a` has an element that is less than the corresponding element in `b`. + If the first `min(a.length, b.length)` elements do not differ, then the shorter array is the lexicographically smaller one. + +**Example 1:** + +**Input:** intervals = [[1,3,2],[4,5,2],[1,5,5],[6,9,3],[6,7,1],[8,9,1]] + +**Output:** [2,3] + +**Explanation:** + +You can choose the intervals with indices 2, and 3 with respective weights of 5, and 3. + +**Example 2:** + +**Input:** intervals = [[5,8,1],[6,7,7],[4,7,3],[9,10,6],[7,8,2],[11,14,3],[3,5,5]] + +**Output:** [1,3,5,6] + +**Explanation:** + +You can choose the intervals with indices 1, 3, 5, and 6 with respective weights of 7, 6, 3, and 5. + +**Constraints:** + +* 1 <= intevals.length <= 5 * 104 +* `intervals[i].length == 3` +* intervals[i] = [li, ri, weighti] +* 1 <= li <= ri <= 109 +* 1 <= weighti <= 109 \ No newline at end of file diff --git a/src/test/java/g3401_3500/s3407_substring_matching_pattern/SolutionTest.java b/src/test/java/g3401_3500/s3407_substring_matching_pattern/SolutionTest.java new file mode 100644 index 000000000..3fe9b16ec --- /dev/null +++ b/src/test/java/g3401_3500/s3407_substring_matching_pattern/SolutionTest.java @@ -0,0 +1,23 @@ +package g3401_3500.s3407_substring_matching_pattern; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void hasMatch() { + assertThat(new Solution().hasMatch("leetcode", "ee*e"), equalTo(true)); + } + + @Test + void hasMatch2() { + assertThat(new Solution().hasMatch("car", "c*v"), equalTo(false)); + } + + @Test + void hasMatch3() { + assertThat(new Solution().hasMatch("luck", "u*"), equalTo(true)); + } +} diff --git a/src/test/java/g3401_3500/s3408_design_task_manager/TaskManagerTest.java b/src/test/java/g3401_3500/s3408_design_task_manager/TaskManagerTest.java new file mode 100644 index 000000000..39473418d --- /dev/null +++ b/src/test/java/g3401_3500/s3408_design_task_manager/TaskManagerTest.java @@ -0,0 +1,29 @@ +package g3401_3500.s3408_design_task_manager; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class TaskManagerTest { + @Test + void test() { + // Initializes with three tasks for Users 1, 2, and 3. + TaskManager taskManager = + new TaskManager( + List.of(List.of(1, 101, 10), List.of(2, 102, 20), List.of(3, 103, 15))); + // Adds task 104 with priority 5 for User 4. + taskManager.add(4, 104, 5); + // Updates priority of task 102 to 8. + taskManager.edit(102, 8); + // return 3. Executes task 103 for User 3. + assertThat(taskManager.execTop(), equalTo(3)); + // Removes task 101 from the system. + taskManager.rmv(101); + // Adds task 105 with priority 15 for User 5. + taskManager.add(5, 105, 15); + // return 5. Executes task 105 for User 5. + assertThat(taskManager.execTop(), equalTo(5)); + } +} diff --git a/src/test/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/SolutionTest.java b/src/test/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/SolutionTest.java new file mode 100644 index 000000000..84ad1e3d0 --- /dev/null +++ b/src/test/java/g3401_3500/s3409_longest_subsequence_with_decreasing_adjacent_difference/SolutionTest.java @@ -0,0 +1,24 @@ +package g3401_3500.s3409_longest_subsequence_with_decreasing_adjacent_difference; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void longestSubsequence() { + assertThat(new Solution().longestSubsequence(new int[] {16, 6, 3}), equalTo(3)); + } + + @Test + void longestSubsequence2() { + assertThat(new Solution().longestSubsequence(new int[] {6, 5, 3, 4, 2, 1}), equalTo(4)); + } + + @Test + void longestSubsequence3() { + assertThat( + new Solution().longestSubsequence(new int[] {10, 20, 10, 19, 10, 20}), equalTo(5)); + } +} diff --git a/src/test/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/SolutionTest.java b/src/test/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/SolutionTest.java new file mode 100644 index 000000000..48cd4117a --- /dev/null +++ b/src/test/java/g3401_3500/s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element/SolutionTest.java @@ -0,0 +1,18 @@ +package g3401_3500.s3410_maximize_subarray_sum_after_removing_all_occurrences_of_one_element; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxSubarraySum() { + assertThat(new Solution().maxSubarraySum(new int[] {-3, 2, -2, -1, 3, -2, 3}), equalTo(7L)); + } + + @Test + void maxSubarraySum2() { + assertThat(new Solution().maxSubarraySum(new int[] {1, 2, 3, 4}), equalTo(10L)); + } +} diff --git a/src/test/java/g3401_3500/s3411_maximum_subarray_with_equal_products/SolutionTest.java b/src/test/java/g3401_3500/s3411_maximum_subarray_with_equal_products/SolutionTest.java new file mode 100644 index 000000000..30ed44e2e --- /dev/null +++ b/src/test/java/g3401_3500/s3411_maximum_subarray_with_equal_products/SolutionTest.java @@ -0,0 +1,23 @@ +package g3401_3500.s3411_maximum_subarray_with_equal_products; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxLength() { + assertThat(new Solution().maxLength(new int[] {1, 2, 1, 2, 1, 1, 1}), equalTo(5)); + } + + @Test + void maxLength2() { + assertThat(new Solution().maxLength(new int[] {2, 3, 4, 5, 6}), equalTo(3)); + } + + @Test + void maxLength3() { + assertThat(new Solution().maxLength(new int[] {1, 2, 3, 1, 4, 5, 1}), equalTo(5)); + } +} diff --git a/src/test/java/g3401_3500/s3412_find_mirror_score_of_a_string/SolutionTest.java b/src/test/java/g3401_3500/s3412_find_mirror_score_of_a_string/SolutionTest.java new file mode 100644 index 000000000..bad7d9efc --- /dev/null +++ b/src/test/java/g3401_3500/s3412_find_mirror_score_of_a_string/SolutionTest.java @@ -0,0 +1,18 @@ +package g3401_3500.s3412_find_mirror_score_of_a_string; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void calculateScore() { + assertThat(new Solution().calculateScore("aczzx"), equalTo(5L)); + } + + @Test + void calculateScore2() { + assertThat(new Solution().calculateScore("abcdef"), equalTo(0L)); + } +} diff --git a/src/test/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/SolutionTest.java b/src/test/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/SolutionTest.java new file mode 100644 index 000000000..e7b3532fe --- /dev/null +++ b/src/test/java/g3401_3500/s3413_maximum_coins_from_k_consecutive_bags/SolutionTest.java @@ -0,0 +1,20 @@ +package g3401_3500.s3413_maximum_coins_from_k_consecutive_bags; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumCoins() { + assertThat( + new Solution().maximumCoins(new int[][] {{8, 10, 1}, {1, 3, 2}, {5, 6, 4}}, 4), + equalTo(10L)); + } + + @Test + void maximumCoins2() { + assertThat(new Solution().maximumCoins(new int[][] {{1, 10, 3}}, 2), equalTo(6L)); + } +} diff --git a/src/test/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/SolutionTest.java b/src/test/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/SolutionTest.java new file mode 100644 index 000000000..65a19289a --- /dev/null +++ b/src/test/java/g3401_3500/s3414_maximum_score_of_non_overlapping_intervals/SolutionTest.java @@ -0,0 +1,65 @@ +package g3401_3500.s3414_maximum_score_of_non_overlapping_intervals; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumWeight() { + assertThat( + new Solution() + .maximumWeight( + List.of( + List.of(1, 3, 2), + List.of(4, 5, 2), + List.of(1, 5, 5), + List.of(6, 9, 3), + List.of(6, 7, 1), + List.of(8, 9, 1))), + equalTo(new int[] {2, 3})); + } + + @Test + void maximumWeight2() { + assertThat( + new Solution() + .maximumWeight( + List.of( + List.of(5, 8, 1), + List.of(6, 7, 7), + List.of(4, 7, 3), + List.of(9, 10, 6), + List.of(7, 8, 2), + List.of(11, 14, 3), + List.of(3, 5, 5))), + equalTo(new int[] {1, 3, 5, 6})); + } + + @Test + void maximumWeight3() { + assertThat( + new Solution() + .maximumWeight( + List.of(List.of(4, 4, 1), List.of(2, 5, 3), List.of(2, 3, 2))), + equalTo(new int[] {0, 2})); + } + + @Test + void maximumWeight4() { + assertThat( + new Solution() + .maximumWeight( + List.of( + List.of(19, 23, 23), + List.of(19, 23, 40), + List.of(1, 16, 31), + List.of(16, 18, 31), + List.of(14, 20, 22), + List.of(14, 22, 5), + List.of(23, 24, 23))), + equalTo(new int[] {1, 2})); + } +}