Skip to content

Commit a12f890

Browse files
committed
Added tasks 3507-3510
1 parent b98fbb2 commit a12f890

File tree

5 files changed

+642
-0
lines changed
  • src/main/java/g3501_3600
    • s3507_minimum_pair_removal_to_sort_array_i
    • s3508_implement_router
    • s3509_maximum_product_of_subsequences_with_an_alternating_sum_equal_to_k
    • s3510_minimum_pair_removal_to_sort_array_ii

5 files changed

+642
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2088,6 +2088,10 @@
20882088

20892089
| # | Title | Difficulty | Tag | Time, ms | Time, %
20902090
|------|----------------|-------------|-------------|----------|--------
2091+
| 3510 |[Minimum Pair Removal to Sort Array II](src/main/java/g3501_3600/s3510_minimum_pair_removal_to_sort_array_ii)| Hard | Array, Hash_Table, Heap_Priority_Queue, Simulation, Linked_List, Ordered_Set, Doubly_Linked_List | 289 | 99.58
2092+
| 3509 |[Maximum Product of Subsequences With an Alternating Sum Equal to K](src/main/java/g3501_3600/s3509_maximum_product_of_subsequences_with_an_alternating_sum_equal_to_k)| Hard | Array, Hash_Table, Dynamic_Programming | 141 | 89.52
2093+
| 3508 |[Implement Router](src/main/java/g3501_3600/s3508_implement_router)| Medium | Array, Hash_Table, Binary_Search, Design, Ordered_Set, Queue | 137 | 100.00
2094+
| 3507 |[Minimum Pair Removal to Sort Array I](src/main/java/g3501_3600/s3507_minimum_pair_removal_to_sort_array_i)| Easy | Array, Hash_Table, Heap_Priority_Queue, Simulation, Linked_List, Ordered_Set, Doubly_Linked_List | 1 | 100.00
20912095
| 3505 |[Minimum Operations to Make Elements Within K Subarrays Equal](src/main/java/g3501_3600/s3505_minimum_operations_to_make_elements_within_k_subarrays_equal)| Hard | Array, Hash_Table, Dynamic_Programming, Math, Heap_Priority_Queue, Sliding_Window | 547 | 77.95
20922096
| 3504 |[Longest Palindrome After Substring Concatenation II](src/main/java/g3501_3600/s3504_longest_palindrome_after_substring_concatenation_ii)| Hard | String, Dynamic_Programming, Two_Pointers | 25 | 99.50
20932097
| 3503 |[Longest Palindrome After Substring Concatenation I](src/main/java/g3501_3600/s3503_longest_palindrome_after_substring_concatenation_i)| Medium | String, Dynamic_Programming, Two_Pointers, Enumeration | 30 | 97.15
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork)
3+
4+
## 3507\. Minimum Pair Removal to Sort Array I
5+
6+
Easy
7+
8+
Given an array `nums`, you can perform the following operation any number of times:
9+
10+
* Select the **adjacent** pair with the **minimum** sum in `nums`. If multiple such pairs exist, choose the leftmost one.
11+
* Replace the pair with their sum.
12+
13+
Return the **minimum number of operations** needed to make the array **non-decreasing**.
14+
15+
An array is said to be **non-decreasing** if each element is greater than or equal to its previous element (if it exists).
16+
17+
**Example 1:**
18+
19+
**Input:** nums = [5,2,3,1]
20+
21+
**Output:** 2
22+
23+
**Explanation:**
24+
25+
* The pair `(3,1)` has the minimum sum of 4. After replacement, `nums = [5,2,4]`.
26+
* The pair `(2,4)` has the minimum sum of 6. After replacement, `nums = [5,6]`.
27+
28+
The array `nums` became non-decreasing in two operations.
29+
30+
**Example 2:**
31+
32+
**Input:** nums = [1,2,2]
33+
34+
**Output:** 0
35+
36+
**Explanation:**
37+
38+
The array `nums` is already sorted.
39+
40+
**Constraints:**
41+
42+
* `1 <= nums.length <= 50`
43+
* `-1000 <= nums[i] <= 1000`
44+
45+
## Solution
46+
47+
```java
48+
public class Solution {
49+
public int minimumPairRemoval(int[] nums) {
50+
int operations = 0;
51+
while (!isNonDecreasing(nums)) {
52+
int minSum = Integer.MAX_VALUE;
53+
int index = 0;
54+
// Find the leftmost pair with minimum sum
55+
for (int i = 0; i < nums.length - 1; i++) {
56+
int sum = nums[i] + nums[i + 1];
57+
if (sum < minSum) {
58+
minSum = sum;
59+
index = i;
60+
}
61+
}
62+
// Merge the pair at index
63+
int[] newNums = new int[nums.length - 1];
64+
int j = 0;
65+
int i = 0;
66+
while (i < nums.length) {
67+
if (i == index) {
68+
newNums[j++] = nums[i] + nums[i + 1];
69+
// Skip the next one since it's merged
70+
i++;
71+
} else {
72+
newNums[j++] = nums[i];
73+
}
74+
i++;
75+
}
76+
nums = newNums;
77+
operations++;
78+
}
79+
return operations;
80+
}
81+
82+
private boolean isNonDecreasing(int[] nums) {
83+
for (int i = 1; i < nums.length; i++) {
84+
if (nums[i] < nums[i - 1]) {
85+
return false;
86+
}
87+
}
88+
return true;
89+
}
90+
}
91+
```
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork)
3+
4+
## 3508\. Implement Router
5+
6+
Medium
7+
8+
Design a data structure that can efficiently manage data packets in a network router. Each data packet consists of the following attributes:
9+
10+
* `source`: A unique identifier for the machine that generated the packet.
11+
* `destination`: A unique identifier for the target machine.
12+
* `timestamp`: The time at which the packet arrived at the router.
13+
14+
Implement the `Router` class:
15+
16+
`Router(int memoryLimit)`: Initializes the Router object with a fixed memory limit.
17+
18+
* `memoryLimit` is the **maximum** number of packets the router can store at any given time.
19+
* If adding a new packet would exceed this limit, the **oldest** packet must be removed to free up space.
20+
21+
`bool addPacket(int source, int destination, int timestamp)`: Adds a packet with the given attributes to the router.
22+
23+
* A packet is considered a duplicate if another packet with the same `source`, `destination`, and `timestamp` already exists in the router.
24+
* Return `true` if the packet is successfully added (i.e., it is not a duplicate); otherwise return `false`.
25+
26+
`int[] forwardPacket()`: Forwards the next packet in FIFO (First In First Out) order.
27+
28+
* Remove the packet from storage.
29+
* Return the packet as an array `[source, destination, timestamp]`.
30+
* If there are no packets to forward, return an empty array.
31+
32+
`int getCount(int destination, int startTime, int endTime)`:
33+
34+
* Returns the number of packets currently stored in the router (i.e., not yet forwarded) that have the specified destination and have timestamps in the inclusive range `[startTime, endTime]`.
35+
36+
**Note** that queries for `addPacket` will be made in increasing order of `timestamp`.
37+
38+
**Example 1:**
39+
40+
**Input:**
41+
["Router", "addPacket", "addPacket", "addPacket", "addPacket", "addPacket", "forwardPacket", "addPacket", "getCount"]
42+
[[3], [1, 4, 90], [2, 5, 90], [1, 4, 90], [3, 5, 95], [4, 5, 105], [], [5, 2, 110], [5, 100, 110]]
43+
44+
**Output:**
45+
[null, true, true, false, true, true, [2, 5, 90], true, 1]
46+
47+
**Explanation**
48+
49+
Router router = new Router(3); // Initialize Router with memoryLimit of 3.
50+
router.addPacket(1, 4, 90); // Packet is added. Return True.
51+
router.addPacket(2, 5, 90); // Packet is added. Return True.
52+
router.addPacket(1, 4, 90); // This is a duplicate packet. Return False.
53+
router.addPacket(3, 5, 95); // Packet is added. Return True
54+
router.addPacket(4, 5, 105); // Packet is added, `[1, 4, 90]` is removed as number of packets exceeds memoryLimit. Return True.
55+
router.forwardPacket(); // Return `[2, 5, 90]` and remove it from router.
56+
router.addPacket(5, 2, 110); // Packet is added. Return True.
57+
router.getCount(5, 100, 110); // The only packet with destination 5 and timestamp in the inclusive range `[100, 110]` is `[4, 5, 105]`. Return 1.
58+
59+
**Example 2:**
60+
61+
**Input:**
62+
["Router", "addPacket", "forwardPacket", "forwardPacket"]
63+
[[2], [7, 4, 90], [], []]
64+
65+
**Output:**
66+
[null, true, [7, 4, 90], []]
67+
68+
**Explanation**
69+
70+
Router router = new Router(2); // Initialize `Router` with `memoryLimit` of 2.
71+
router.addPacket(7, 4, 90); // Return True.
72+
router.forwardPacket(); // Return `[7, 4, 90]`.
73+
router.forwardPacket(); // There are no packets left, return `[]`.
74+
75+
**Constraints:**
76+
77+
* <code>2 <= memoryLimit <= 10<sup>5</sup></code>
78+
* <code>1 <= source, destination <= 2 * 10<sup>5</sup></code>
79+
* <code>1 <= timestamp <= 10<sup>9</sup></code>
80+
* <code>1 <= startTime <= endTime <= 10<sup>9</sup></code>
81+
* At most <code>10<sup>5</sup></code> calls will be made to `addPacket`, `forwardPacket`, and `getCount` methods altogether.
82+
* queries for `addPacket` will be made in increasing order of `timestamp`.
83+
84+
## Solution
85+
86+
```java
87+
import java.util.ArrayList;
88+
import java.util.HashMap;
89+
import java.util.LinkedList;
90+
import java.util.Queue;
91+
92+
@SuppressWarnings("java:S135")
93+
public class Router {
94+
private final int size;
95+
private int cur;
96+
private final Queue<int[]> q;
97+
private final HashMap<Integer, ArrayList<int[]>> map;
98+
99+
public Router(int memoryLimit) {
100+
q = new LinkedList<>();
101+
map = new HashMap<>();
102+
size = memoryLimit;
103+
cur = 0;
104+
}
105+
106+
public boolean addPacket(int source, int destination, int timestamp) {
107+
if (map.containsKey(destination)) {
108+
boolean found = false;
109+
ArrayList<int[]> list = map.get(destination);
110+
for (int i = list.size() - 1; i >= 0; i--) {
111+
if (list.get(i)[1] < timestamp) {
112+
break;
113+
} else if (list.get(i)[0] == source) {
114+
found = true;
115+
break;
116+
}
117+
}
118+
if (found) {
119+
return false;
120+
}
121+
}
122+
if (map.containsKey(destination)) {
123+
ArrayList<int[]> list = map.get(destination);
124+
list.add(new int[] {source, timestamp});
125+
cur++;
126+
q.offer(new int[] {source, destination, timestamp});
127+
} else {
128+
ArrayList<int[]> temp = new ArrayList<>();
129+
temp.add(new int[] {source, timestamp});
130+
cur++;
131+
map.put(destination, temp);
132+
q.offer(new int[] {source, destination, timestamp});
133+
}
134+
if (cur > size) {
135+
forwardPacket();
136+
}
137+
return true;
138+
}
139+
140+
public int[] forwardPacket() {
141+
if (q.isEmpty()) {
142+
return new int[] {};
143+
}
144+
int[] temp = q.poll();
145+
ArrayList<int[]> list = map.get(temp[1]);
146+
list.remove(0);
147+
if (list.isEmpty()) {
148+
map.remove(temp[1]);
149+
}
150+
cur--;
151+
return temp;
152+
}
153+
154+
public int getCount(int destination, int startTime, int endTime) {
155+
if (map.containsKey(destination)) {
156+
ArrayList<int[]> list = map.get(destination);
157+
int lower = -1;
158+
int higher = -1;
159+
for (int i = 0; i < list.size(); i++) {
160+
if (list.get(i)[1] >= startTime) {
161+
lower = i;
162+
break;
163+
}
164+
}
165+
for (int i = list.size() - 1; i >= 0; i--) {
166+
if (list.get(i)[1] <= endTime) {
167+
higher = i;
168+
break;
169+
}
170+
}
171+
if (lower == -1 || higher == -1) {
172+
return 0;
173+
} else {
174+
return Math.max(0, higher - lower + 1);
175+
}
176+
} else {
177+
return 0;
178+
}
179+
}
180+
}
181+
182+
/*
183+
* Your Router object will be instantiated and called as such:
184+
* Router obj = new Router(memoryLimit);
185+
* boolean param_1 = obj.addPacket(source,destination,timestamp);
186+
* int[] param_2 = obj.forwardPacket();
187+
* int param_3 = obj.getCount(destination,startTime,endTime);
188+
*/
189+
```

0 commit comments

Comments
 (0)