Skip to content

Commit 902bbb9

Browse files
committed
Added tasks 3507-3510
1 parent 3aa902a commit 902bbb9

File tree

5 files changed

+638
-0
lines changed
  • src/main/kotlin/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

+638
-0
lines changed

README.md

+4
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/kotlin/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 | 219 | 100.00
2092+
| 3509 |[Maximum Product of Subsequences With an Alternating Sum Equal to K](src/main/kotlin/g3501_3600/s3509_maximum_product_of_subsequences_with_an_alternating_sum_equal_to_k)| Hard | Array, Hash_Table, Dynamic_Programming | 99 | 96.30
2093+
| 3508 |[Implement Router](src/main/kotlin/g3501_3600/s3508_implement_router)| Medium | Array, Hash_Table, Binary_Search, Design, Ordered_Set, Queue | 202 | 100.00
2094+
| 3507 |[Minimum Pair Removal to Sort Array I](src/main/kotlin/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 | 2 | 100.00
20912095
| 3505 |[Minimum Operations to Make Elements Within K Subarrays Equal](src/main/kotlin/g3501_3600/s3505_minimum_operations_to_make_elements_within_k_subarrays_equal)| Hard | Array, Hash_Table, Dynamic_Programming, Math, Heap_Priority_Queue, Sliding_Window | 537 | 100.00
20922096
| 3504 |[Longest Palindrome After Substring Concatenation II](src/main/kotlin/g3501_3600/s3504_longest_palindrome_after_substring_concatenation_ii)| Hard | String, Dynamic_Programming, Two_Pointers | 59 | 100.00
20932097
| 3503 |[Longest Palindrome After Substring Concatenation I](src/main/kotlin/g3501_3600/s3503_longest_palindrome_after_substring_concatenation_i)| Medium | String, Dynamic_Programming, Two_Pointers, Enumeration | 42 | 83.33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](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)
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+
```kotlin
48+
class Solution {
49+
fun minimumPairRemoval(nums: IntArray): Int {
50+
var nums = nums
51+
var operations = 0
52+
while (!isNonDecreasing(nums)) {
53+
var minSum = Int.Companion.MAX_VALUE
54+
var index = 0
55+
// Find the leftmost pair with minimum sum
56+
for (i in 0..<nums.size - 1) {
57+
val sum = nums[i] + nums[i + 1]
58+
if (sum < minSum) {
59+
minSum = sum
60+
index = i
61+
}
62+
}
63+
// Merge the pair at index
64+
val newNums = IntArray(nums.size - 1)
65+
var j = 0
66+
var i = 0
67+
while (i < nums.size) {
68+
if (i == index) {
69+
newNums[j++] = nums[i] + nums[i + 1]
70+
// Skip the next one since it's merged
71+
i++
72+
} else {
73+
newNums[j++] = nums[i]
74+
}
75+
i++
76+
}
77+
nums = newNums
78+
operations++
79+
}
80+
return operations
81+
}
82+
83+
private fun isNonDecreasing(nums: IntArray): Boolean {
84+
for (i in 1..<nums.size) {
85+
if (nums[i] < nums[i - 1]) {
86+
return false
87+
}
88+
}
89+
return true
90+
}
91+
}
92+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](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)
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+
```kotlin
87+
import java.util.LinkedList
88+
import java.util.Queue
89+
import kotlin.math.max
90+
91+
class Router(private val size: Int) {
92+
private var cur = 0
93+
private val q: Queue<IntArray>
94+
private val map: HashMap<Int, ArrayList<IntArray>>
95+
96+
init {
97+
q = LinkedList<IntArray>()
98+
map = HashMap<Int, ArrayList<IntArray>>()
99+
}
100+
101+
fun addPacket(source: Int, destination: Int, timestamp: Int): Boolean {
102+
if (map.containsKey(destination)) {
103+
var found = false
104+
val list: ArrayList<IntArray> = map[destination]!!
105+
for (i in list.indices.reversed()) {
106+
if (list[i][1] < timestamp) {
107+
break
108+
} else if (list[i][0] == source) {
109+
found = true
110+
break
111+
}
112+
}
113+
if (found) {
114+
return false
115+
}
116+
}
117+
if (map.containsKey(destination)) {
118+
val list: ArrayList<IntArray> = map[destination]!!
119+
list.add(intArrayOf(source, timestamp))
120+
cur++
121+
q.offer(intArrayOf(source, destination, timestamp))
122+
} else {
123+
val temp = ArrayList<IntArray>()
124+
temp.add(intArrayOf(source, timestamp))
125+
cur++
126+
map.put(destination, temp)
127+
q.offer(intArrayOf(source, destination, timestamp))
128+
}
129+
if (cur > size) {
130+
forwardPacket()
131+
}
132+
return true
133+
}
134+
135+
fun forwardPacket(): IntArray? {
136+
if (q.isEmpty()) {
137+
return intArrayOf()
138+
}
139+
val temp = q.poll()
140+
val list: ArrayList<IntArray> = map[temp[1]]!!
141+
list.removeAt(0)
142+
if (list.isEmpty()) {
143+
map.remove(temp[1])
144+
}
145+
cur--
146+
return temp
147+
}
148+
149+
fun getCount(destination: Int, startTime: Int, endTime: Int): Int {
150+
return if (map.containsKey(destination)) {
151+
val list: ArrayList<IntArray> = map[destination]!!
152+
var lower = -1
153+
var higher = -1
154+
for (i in list.indices) {
155+
if (list[i][1] >= startTime) {
156+
lower = i
157+
break
158+
}
159+
}
160+
for (i in list.indices.reversed()) {
161+
if (list[i][1] <= endTime) {
162+
higher = i
163+
break
164+
}
165+
}
166+
if (lower == -1 || higher == -1) {
167+
0
168+
} else {
169+
max(0.0, (higher - lower + 1).toDouble()).toInt()
170+
}
171+
} else {
172+
0
173+
}
174+
}
175+
}
176+
177+
/*
178+
* Your Router object will be instantiated and called as such:
179+
* var obj = Router(memoryLimit)
180+
* var param_1 = obj.addPacket(source,destination,timestamp)
181+
* var param_2 = obj.forwardPacket()
182+
* var param_3 = obj.getCount(destination,startTime,endTime)
183+
*/
184+
```

0 commit comments

Comments
 (0)