Skip to content

Commit 4fef2ec

Browse files
authored
Added tasks 3280-3283
1 parent dac0f07 commit 4fef2ec

File tree

5 files changed

+355
-0
lines changed
  • src/main/kotlin/g3201_3300
    • s3280_convert_date_to_binary
    • s3281_maximize_score_of_numbers_in_ranges
    • s3282_reach_end_of_array_with_max_score
    • s3283_maximum_number_of_moves_to_kill_all_pawns

5 files changed

+355
-0
lines changed

README.md

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

18171817
| # | Title | Difficulty | Tag | Time, ms | Time, %
18181818
|------|----------------|-------------|-------------|----------|--------
1819+
| 3283 |[Maximum Number of Moves to Kill All Pawns](src/main/kotlin/g3201_3300/s3283_maximum_number_of_moves_to_kill_all_pawns)| Hard | Array, Math, Breadth_First_Search, Bit_Manipulation, Bitmask, Game_Theory | 638 | 100.00
1820+
| 3282 |[Reach End of Array With Max Score](src/main/kotlin/g3201_3300/s3282_reach_end_of_array_with_max_score)| Medium | Array, Greedy | 789 | 90.91
1821+
| 3281 |[Maximize Score of Numbers in Ranges](src/main/kotlin/g3201_3300/s3281_maximize_score_of_numbers_in_ranges)| Medium | Array, Sorting, Greedy, Binary_Search | 710 | 88.24
1822+
| 3280 |[Convert Date to Binary](src/main/kotlin/g3201_3300/s3280_convert_date_to_binary)| Easy | String, Math | 174 | 79.31
18191823
| 3277 |[Maximum XOR Score Subarray Queries](src/main/kotlin/g3201_3300/s3277_maximum_xor_score_subarray_queries)| Hard | Array, Dynamic_Programming | 1269 | 100.00
18201824
| 3276 |[Select Cells in Grid With Maximum Score](src/main/kotlin/g3201_3300/s3276_select_cells_in_grid_with_maximum_score)| Hard | Array, Dynamic_Programming, Matrix, Bit_Manipulation, Bitmask | 213 | 92.31
18211825
| 3275 |[K-th Nearest Obstacle Queries](src/main/kotlin/g3201_3300/s3275_k_th_nearest_obstacle_queries)| Medium | Array, Heap_Priority_Queue | 1277 | 100.00
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
## 3280\. Convert Date to Binary
5+
6+
Easy
7+
8+
You are given a string `date` representing a Gregorian calendar date in the `yyyy-mm-dd` format.
9+
10+
`date` can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in `year-month-day` format.
11+
12+
Return the **binary** representation of `date`.
13+
14+
**Example 1:**
15+
16+
**Input:** date = "2080-02-29"
17+
18+
**Output:** "100000100000-10-11101"
19+
20+
**Explanation:**
21+
22+
100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.
23+
24+
**Example 2:**
25+
26+
**Input:** date = "1900-01-01"
27+
28+
**Output:** "11101101100-1-1"
29+
30+
**Explanation:**
31+
32+
11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.
33+
34+
**Constraints:**
35+
36+
* `date.length == 10`
37+
* `date[4] == date[7] == '-'`, and all other `date[i]`'s are digits.
38+
* The input is generated such that `date` represents a valid Gregorian calendar date between Jan 1<sup>st</sup>, 1900 and Dec 31<sup>st</sup>, 2100 (both inclusive).
39+
40+
## Solution
41+
42+
```kotlin
43+
class Solution {
44+
fun convertDateToBinary(dat: String): String {
45+
val str = StringBuilder()
46+
val res = StringBuilder()
47+
for (c in dat.toCharArray()) {
48+
if (c.isDigit()) {
49+
str.append(c)
50+
} else if (c == '-') {
51+
res.append(str.toString().toInt().toString(2))
52+
res.append('-')
53+
str.setLength(0)
54+
}
55+
}
56+
if (str.isNotEmpty()) {
57+
res.append(str.toString().toInt().toString(2))
58+
}
59+
return res.toString()
60+
}
61+
}
62+
```
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
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+
## 3281\. Maximize Score of Numbers in Ranges
5+
6+
Medium
7+
8+
You are given an array of integers `start` and an integer `d`, representing `n` intervals `[start[i], start[i] + d]`.
9+
10+
You are asked to choose `n` integers where the <code>i<sup>th</sup></code> integer must belong to the <code>i<sup>th</sup></code> interval. The **score** of the chosen integers is defined as the **minimum** absolute difference between any two integers that have been chosen.
11+
12+
Return the **maximum** _possible score_ of the chosen integers.
13+
14+
**Example 1:**
15+
16+
**Input:** start = [6,0,3], d = 2
17+
18+
**Output:** 4
19+
20+
**Explanation:**
21+
22+
The maximum possible score can be obtained by choosing integers: 8, 0, and 4. The score of these chosen integers is `min(|8 - 0|, |8 - 4|, |0 - 4|)` which equals 4.
23+
24+
**Example 2:**
25+
26+
**Input:** start = [2,6,13,13], d = 5
27+
28+
**Output:** 5
29+
30+
**Explanation:**
31+
32+
The maximum possible score can be obtained by choosing integers: 2, 7, 13, and 18. The score of these chosen integers is `min(|2 - 7|, |2 - 13|, |2 - 18|, |7 - 13|, |7 - 18|, |13 - 18|)` which equals 5.
33+
34+
**Constraints:**
35+
36+
* <code>2 <= start.length <= 10<sup>5</sup></code>
37+
* <code>0 <= start[i] <= 10<sup>9</sup></code>
38+
* <code>0 <= d <= 10<sup>9</sup></code>
39+
40+
## Solution
41+
42+
```kotlin
43+
import kotlin.math.max
44+
45+
class Solution {
46+
fun maxPossibleScore(start: IntArray, d: Int): Int {
47+
start.sort()
48+
val n = start.size
49+
var l = 0
50+
var r = start[n - 1] - start[0] + d + 1
51+
while (l < r) {
52+
val m = l + (r - l) / 2
53+
if (isPossible(start, d, m)) {
54+
l = m + 1
55+
} else {
56+
r = m
57+
}
58+
}
59+
return l - 1
60+
}
61+
62+
private fun isPossible(start: IntArray, d: Int, score: Int): Boolean {
63+
var pre = start[0]
64+
for (i in 1 until start.size) {
65+
if (start[i] + d - pre < score) {
66+
return false
67+
}
68+
pre = max(start[i], (pre + score))
69+
}
70+
return true
71+
}
72+
}
73+
```
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
## 3282\. Reach End of Array With Max Score
5+
6+
Medium
7+
8+
You are given an integer array `nums` of length `n`.
9+
10+
Your goal is to start at index `0` and reach index `n - 1`. You can only jump to indices **greater** than your current index.
11+
12+
The score for a jump from index `i` to index `j` is calculated as `(j - i) * nums[i]`.
13+
14+
Return the **maximum** possible **total score** by the time you reach the last index.
15+
16+
**Example 1:**
17+
18+
**Input:** nums = [1,3,1,5]
19+
20+
**Output:** 7
21+
22+
**Explanation:**
23+
24+
First, jump to index 1 and then jump to the last index. The final score is `1 * 1 + 2 * 3 = 7`.
25+
26+
**Example 2:**
27+
28+
**Input:** nums = [4,3,1,3,2]
29+
30+
**Output:** 16
31+
32+
**Explanation:**
33+
34+
Jump directly to the last index. The final score is `4 * 4 = 16`.
35+
36+
**Constraints:**
37+
38+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
39+
* <code>1 <= nums[i] <= 10<sup>5</sup></code>
40+
41+
## Solution
42+
43+
```kotlin
44+
import kotlin.math.max
45+
46+
class Solution {
47+
fun findMaximumScore(nums: List<Int>): Long {
48+
var res: Long = 0
49+
var ma: Long = 0
50+
for (num in nums) {
51+
res += ma
52+
ma = max(ma, num.toLong())
53+
}
54+
return res
55+
}
56+
}
57+
```
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
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+
## 3283\. Maximum Number of Moves to Kill All Pawns
5+
6+
Hard
7+
8+
There is a `50 x 50` chessboard with **one** knight and some pawns on it. You are given two integers `kx` and `ky` where `(kx, ky)` denotes the position of the knight, and a 2D array `positions` where <code>positions[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> denotes the position of the pawns on the chessboard.
9+
10+
Alice and Bob play a _turn-based_ game, where Alice goes first. In each player's turn:
11+
12+
* The player _selects_ a pawn that still exists on the board and captures it with the knight in the **fewest** possible **moves**. **Note** that the player can select **any** pawn, it **might not** be one that can be captured in the **least** number of moves.
13+
* In the process of capturing the _selected_ pawn, the knight **may** pass other pawns **without** capturing them. **Only** the _selected_ pawn can be captured in _this_ turn.
14+
15+
Alice is trying to **maximize** the **sum** of the number of moves made by _both_ players until there are no more pawns on the board, whereas Bob tries to **minimize** them.
16+
17+
Return the **maximum** _total_ number of moves made during the game that Alice can achieve, assuming both players play **optimally**.
18+
19+
Note that in one **move,** a chess knight has eight possible positions it can move to, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
20+
21+
![](https://assets.leetcode.com/uploads/2024/08/01/chess_knight.jpg)
22+
23+
**Example 1:**
24+
25+
**Input:** kx = 1, ky = 1, positions = \[\[0,0]]
26+
27+
**Output:** 4
28+
29+
**Explanation:**
30+
31+
![](https://assets.leetcode.com/uploads/2024/08/16/gif3.gif)
32+
33+
The knight takes 4 moves to reach the pawn at `(0, 0)`.
34+
35+
**Example 2:**
36+
37+
**Input:** kx = 0, ky = 2, positions = \[\[1,1],[2,2],[3,3]]
38+
39+
**Output:** 8
40+
41+
**Explanation:**
42+
43+
**![](https://assets.leetcode.com/uploads/2024/08/16/gif4.gif)**
44+
45+
* Alice picks the pawn at `(2, 2)` and captures it in two moves: `(0, 2) -> (1, 4) -> (2, 2)`.
46+
* Bob picks the pawn at `(3, 3)` and captures it in two moves: `(2, 2) -> (4, 1) -> (3, 3)`.
47+
* Alice picks the pawn at `(1, 1)` and captures it in four moves: `(3, 3) -> (4, 1) -> (2, 2) -> (0, 3) -> (1, 1)`.
48+
49+
**Example 3:**
50+
51+
**Input:** kx = 0, ky = 0, positions = \[\[1,2],[2,4]]
52+
53+
**Output:** 3
54+
55+
**Explanation:**
56+
57+
* Alice picks the pawn at `(2, 4)` and captures it in two moves: `(0, 0) -> (1, 2) -> (2, 4)`. Note that the pawn at `(1, 2)` is not captured.
58+
* Bob picks the pawn at `(1, 2)` and captures it in one move: `(2, 4) -> (1, 2)`.
59+
60+
**Constraints:**
61+
62+
* `0 <= kx, ky <= 49`
63+
* `1 <= positions.length <= 15`
64+
* `positions[i].length == 2`
65+
* `0 <= positions[i][0], positions[i][1] <= 49`
66+
* All `positions[i]` are unique.
67+
* The input is generated such that `positions[i] != [kx, ky]` for all `0 <= i < positions.length`.
68+
69+
## Solution
70+
71+
```kotlin
72+
import java.util.LinkedList
73+
import java.util.Queue
74+
import kotlin.math.max
75+
import kotlin.math.min
76+
77+
class Solution {
78+
private lateinit var distances: Array<IntArray>
79+
private lateinit var memo: Array<Array<Int?>?>
80+
81+
fun maxMoves(kx: Int, ky: Int, positions: Array<IntArray>): Int {
82+
val n = positions.size
83+
distances = Array<IntArray>(n + 1) { IntArray(n + 1) { 0 } }
84+
memo = Array<Array<Int?>?>(n + 1) { arrayOfNulls<Int>(1 shl n) }
85+
// Calculate distances between all pairs of positions (including knight's initial position)
86+
for (i in 0 until n) {
87+
distances[n][i] = calculateMoves(kx, ky, positions[i][0], positions[i][1])
88+
for (j in i + 1 until n) {
89+
val dist =
90+
calculateMoves(
91+
positions[i][0], positions[i][1], positions[j][0], positions[j][1]
92+
)
93+
distances[j][i] = dist
94+
distances[i][j] = distances[j][i]
95+
}
96+
}
97+
return minimax(n, (1 shl n) - 1, true)
98+
}
99+
100+
private fun minimax(lastPos: Int, remainingPawns: Int, isAlice: Boolean): Int {
101+
if (remainingPawns == 0) {
102+
return 0
103+
}
104+
if (memo[lastPos]!![remainingPawns] != null) {
105+
return memo[lastPos]!![remainingPawns]!!
106+
}
107+
var result = if (isAlice) 0 else Int.Companion.MAX_VALUE
108+
for (i in 0 until distances.size - 1) {
109+
if ((remainingPawns and (1 shl i)) != 0) {
110+
val newRemainingPawns = remainingPawns and (1 shl i).inv()
111+
val moveValue = distances[lastPos][i] + minimax(i, newRemainingPawns, !isAlice)
112+
result = if (isAlice) {
113+
max(result, moveValue)
114+
} else {
115+
min(result, moveValue)
116+
}
117+
}
118+
}
119+
memo[lastPos]!![remainingPawns] = result
120+
return result
121+
}
122+
123+
private fun calculateMoves(x1: Int, y1: Int, x2: Int, y2: Int): Int {
124+
if (x1 == x2 && y1 == y2) {
125+
return 0
126+
}
127+
val visited = Array<BooleanArray?>(50) { BooleanArray(50) }
128+
val queue: Queue<IntArray> = LinkedList<IntArray>()
129+
queue.offer(intArrayOf(x1, y1, 0))
130+
visited[x1]!![y1] = true
131+
while (queue.isNotEmpty()) {
132+
val current = queue.poll()
133+
val x = current[0]
134+
val y = current[1]
135+
val moves = current[2]
136+
for (move in KNIGHT_MOVES) {
137+
val nx = x + move[0]
138+
val ny = y + move[1]
139+
if (nx == x2 && ny == y2) {
140+
return moves + 1
141+
}
142+
if (nx >= 0 && nx < 50 && ny >= 0 && ny < 50 && !visited[nx]!![ny]) {
143+
queue.offer(intArrayOf(nx, ny, moves + 1))
144+
visited[nx]!![ny] = true
145+
}
146+
}
147+
}
148+
// Should never reach here if input is valid
149+
return -1
150+
}
151+
152+
companion object {
153+
private val KNIGHT_MOVES = arrayOf<IntArray>(
154+
intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf(-1, -2), intArrayOf(-1, 2),
155+
intArrayOf(1, -2), intArrayOf(1, 2), intArrayOf(2, -1), intArrayOf(2, 1)
156+
)
157+
}
158+
}
159+
```

0 commit comments

Comments
 (0)