Skip to content

Commit 8da9c0b

Browse files
committed
Added tasks 3423-3426
1 parent e9fc5eb commit 8da9c0b

File tree

12 files changed

+417
-0
lines changed

12 files changed

+417
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package g3401_3500.s3423_maximum_difference_between_adjacent_elements_in_a_circular_array;
2+
3+
// #Easy #2025_01_19_Time_1_(100.00%)_Space_43.31_(100.00%)
4+
5+
public class Solution {
6+
public int maxAdjacentDistance(int[] nums) {
7+
int maxDiff = 0;
8+
for (int i = 0; i < nums.length; i++) {
9+
int nextIndex = (i + 1) % nums.length;
10+
int diff = Math.abs(nums[i] - nums[nextIndex]);
11+
maxDiff = Math.max(maxDiff, diff);
12+
}
13+
return maxDiff;
14+
}
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
3423\. Maximum Difference Between Adjacent Elements in a Circular Array
2+
3+
Easy
4+
5+
Given a **circular** array `nums`, find the **maximum** absolute difference between adjacent elements.
6+
7+
**Note**: In a circular array, the first and last elements are adjacent.
8+
9+
**Example 1:**
10+
11+
**Input:** nums = [1,2,4]
12+
13+
**Output:** 3
14+
15+
**Explanation:**
16+
17+
Because `nums` is circular, `nums[0]` and `nums[2]` are adjacent. They have the maximum absolute difference of `|4 - 1| = 3`.
18+
19+
**Example 2:**
20+
21+
**Input:** nums = [-5,-10,-5]
22+
23+
**Output:** 5
24+
25+
**Explanation:**
26+
27+
The adjacent elements `nums[0]` and `nums[1]` have the maximum absolute difference of `|-5 - (-10)| = 5`.
28+
29+
**Constraints:**
30+
31+
* `2 <= nums.length <= 100`
32+
* `-100 <= nums[i] <= 100`
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package g3401_3500.s3424_minimum_cost_to_make_arrays_identical;
2+
3+
// #Medium #2025_01_19_Time_62_(_%)_Space_57.38_(_%)
4+
5+
import java.util.Arrays;
6+
7+
public class Solution {
8+
public long minCost(int[] arr, int[] brr, long k) {
9+
long res1 = 0;
10+
long res2 = 0;
11+
for (int i = 0; i < arr.length; ++i) {
12+
res1 += Math.abs(arr[i] - brr[i]);
13+
}
14+
Arrays.sort(arr);
15+
Arrays.sort(brr);
16+
for (int i = 0; i < arr.length; ++i) {
17+
res2 += Math.abs(arr[i] - brr[i]);
18+
}
19+
return Math.min(res1, res2 + k);
20+
}
21+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
3424\. Minimum Cost to Make Arrays Identical
2+
3+
Medium
4+
5+
You are given two integer arrays `arr` and `brr` of length `n`, and an integer `k`. You can perform the following operations on `arr` _any_ number of times:
6+
7+
* Split `arr` into _any_ number of **contiguous** **non-empty subarrays** and rearrange these subarrays in _any order_. This operation has a fixed cost of `k`.
8+
* Choose any element in `arr` and add or subtract a positive integer `x` to it. The cost of this operation is `x`.
9+
10+
11+
Return the **minimum** total cost to make `arr` **equal** to `brr`.
12+
13+
**Example 1:**
14+
15+
**Input:** arr = [-7,9,5], brr = [7,-2,-5], k = 2
16+
17+
**Output:** 13
18+
19+
**Explanation:**
20+
21+
* Split `arr` into two contiguous subarrays: `[-7]` and `[9, 5]` and rearrange them as `[9, 5, -7]`, with a cost of 2.
22+
* Subtract 2 from element `arr[0]`. The array becomes `[7, 5, -7]`. The cost of this operation is 2.
23+
* Subtract 7 from element `arr[1]`. The array becomes `[7, -2, -7]`. The cost of this operation is 7.
24+
* Add 2 to element `arr[2]`. The array becomes `[7, -2, -5]`. The cost of this operation is 2.
25+
26+
The total cost to make the arrays equal is `2 + 2 + 7 + 2 = 13`.
27+
28+
**Example 2:**
29+
30+
**Input:** arr = [2,1], brr = [2,1], k = 0
31+
32+
**Output:** 0
33+
34+
**Explanation:**
35+
36+
Since the arrays are already equal, no operations are needed, and the total cost is 0.
37+
38+
**Constraints:**
39+
40+
* <code>1 <= arr.length == brr.length <= 10<sup>5</sup></code>
41+
* <code>0 <= k <= 2 * 10<sup>10</sup></code>
42+
* <code>-10<sup>5</sup> <= arr[i] <= 10<sup>5</sup></code>
43+
* <code>-10<sup>5</sup> <= brr[i] <= 10<sup>5</sup></code>
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package g3401_3500.s3425_longest_special_path;
2+
3+
// #Hard #2025_01_19_Time_57_(100.00%)_Space_94.11_(100.00%)
4+
5+
import java.util.ArrayList;
6+
import java.util.Arrays;
7+
8+
@SuppressWarnings("unchecked")
9+
public class Solution {
10+
private ArrayList<int[]>[] adj;
11+
private int[] nums;
12+
private int[] dist;
13+
private int[] lastOccur;
14+
private ArrayList<Integer> pathStack;
15+
private int minIndex;
16+
private int maxLen;
17+
private int minNodesForMaxLen;
18+
19+
public int[] longestSpecialPath(int[][] edges, int[] nums) {
20+
int n = nums.length;
21+
this.nums = nums;
22+
adj = new ArrayList[n];
23+
for (int i = 0; i < n; i++) {
24+
adj[i] = new ArrayList<>();
25+
}
26+
for (int[] e : edges) {
27+
int u = e[0], v = e[1], w = e[2];
28+
adj[u].add(new int[] {v, w});
29+
adj[v].add(new int[] {u, w});
30+
}
31+
dist = new int[n];
32+
buildDist(0, -1, 0);
33+
int maxVal = 0;
34+
for (int val : nums) {
35+
if (val > maxVal) {
36+
maxVal = val;
37+
}
38+
}
39+
lastOccur = new int[maxVal + 1];
40+
Arrays.fill(lastOccur, -1);
41+
pathStack = new ArrayList<>();
42+
minIndex = 0;
43+
maxLen = 0;
44+
minNodesForMaxLen = Integer.MAX_VALUE;
45+
dfs(0, -1);
46+
return new int[] {maxLen, minNodesForMaxLen};
47+
}
48+
49+
private void buildDist(int u, int parent, int currDist) {
50+
dist[u] = currDist;
51+
for (int[] edge : adj[u]) {
52+
int v = edge[0], w = edge[1];
53+
if (v == parent) continue;
54+
buildDist(v, u, currDist + w);
55+
}
56+
}
57+
58+
private void dfs(int u, int parent) {
59+
int stackPos = pathStack.size();
60+
pathStack.add(u);
61+
int val = nums[u];
62+
int oldPos = lastOccur[val];
63+
int oldMinIndex = minIndex;
64+
lastOccur[val] = stackPos;
65+
if (oldPos >= minIndex) {
66+
minIndex = oldPos + 1;
67+
}
68+
if (minIndex <= stackPos) {
69+
int ancestor = pathStack.get(minIndex);
70+
int pathLength = dist[u] - dist[ancestor];
71+
int pathNodes = stackPos - minIndex + 1;
72+
if (pathLength > maxLen) {
73+
maxLen = pathLength;
74+
minNodesForMaxLen = pathNodes;
75+
} else if (pathLength == maxLen && pathNodes < minNodesForMaxLen) {
76+
minNodesForMaxLen = pathNodes;
77+
}
78+
}
79+
for (int[] edge : adj[u]) {
80+
int v = edge[0];
81+
if (v == parent) continue;
82+
dfs(v, u);
83+
}
84+
pathStack.remove(pathStack.size() - 1);
85+
lastOccur[val] = oldPos;
86+
minIndex = oldMinIndex;
87+
}
88+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
3425\. Longest Special Path
2+
3+
Hard
4+
5+
You are given an undirected tree rooted at node `0` with `n` nodes numbered from `0` to `n - 1`, represented by a 2D array `edges` of length `n - 1`, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code> indicates an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with length <code>length<sub>i</sub></code>. You are also given an integer array `nums`, where `nums[i]` represents the value at node `i`.
6+
7+
A **special path** is defined as a **downward** path from an ancestor node to a descendant node such that all the values of the nodes in that path are **unique**.
8+
9+
**Note** that a path may start and end at the same node.
10+
11+
Return an array `result` of size 2, where `result[0]` is the **length** of the **longest** special path, and `result[1]` is the **minimum** number of nodes in all _possible_ **longest** special paths.
12+
13+
**Example 1:**
14+
15+
**Input:** edges = [[0,1,2],[1,2,3],[1,3,5],[1,4,4],[2,5,6]], nums = [2,1,2,1,3,1]
16+
17+
**Output:** [6,2]
18+
19+
**Explanation:**
20+
21+
#### In the image below, nodes are colored by their corresponding values in `nums`
22+
23+
![](https://assets.leetcode.com/uploads/2024/11/02/tree3.jpeg)
24+
25+
The longest special paths are `2 -> 5` and `0 -> 1 -> 4`, both having a length of 6. The minimum number of nodes across all longest special paths is 2.
26+
27+
**Example 2:**
28+
29+
**Input:** edges = [[1,0,8]], nums = [2,2]
30+
31+
**Output:** [0,1]
32+
33+
**Explanation:**
34+
35+
![](https://assets.leetcode.com/uploads/2024/11/02/tree4.jpeg)
36+
37+
The longest special paths are `0` and `1`, both having a length of 0. The minimum number of nodes across all longest special paths is 1.
38+
39+
**Constraints:**
40+
41+
* <code>2 <= n <= 5 * 10<sup>4</sup></code>
42+
* `edges.length == n - 1`
43+
* `edges[i].length == 3`
44+
* <code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code>
45+
* <code>1 <= length<sub>i</sub> <= 10<sup>3</sup></code>
46+
* `nums.length == n`
47+
* <code>0 <= nums[i] <= 5 * 10<sup>4</sup></code>
48+
* The input is generated such that `edges` represents a valid tree.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package g3401_3500.s3426_manhattan_distances_of_all_arrangements_of_pieces;
2+
3+
// #Hard #2025_01_19_Time_20_(100.00%)_Space_41.18_(100.00%)
4+
5+
public class Solution {
6+
private long comb(long a, long b, long mod) {
7+
if (b > a) return 0;
8+
long numer = 1, denom = 1;
9+
for (long i = 0; i < b; ++i) {
10+
numer = numer * (a - i) % mod;
11+
denom = denom * (i + 1) % mod;
12+
}
13+
long denom_inv = 1;
14+
long exp = mod - 2;
15+
while (exp > 0) {
16+
if (exp % 2 > 0) {
17+
denom_inv = denom_inv * denom % mod;
18+
}
19+
denom = denom * denom % mod;
20+
exp /= 2;
21+
}
22+
return numer * denom_inv % mod;
23+
}
24+
25+
public int distanceSum(int m, int n, int k) {
26+
long res = 0, mod = 1000000007;
27+
long base = comb((long) m * n - 2, k - 2, mod);
28+
for (int d = 1; d < n; ++d) {
29+
res = (res + (long) d * (n - d) % mod * m % mod * m % mod) % mod;
30+
}
31+
for (int d = 1; d < m; ++d) {
32+
res = (res + (long) d * (m - d) % mod * n % mod * n % mod) % mod;
33+
}
34+
return (int) (res * base % mod);
35+
}
36+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
3426\. Manhattan Distances of All Arrangements of Pieces
2+
3+
Hard
4+
5+
You are given three integers `m`, `n`, and `k`.
6+
7+
There is a rectangular grid of size `m × n` containing `k` identical pieces. Return the sum of Manhattan distances between every pair of pieces over all **valid arrangements** of pieces.
8+
9+
A **valid arrangement** is a placement of all `k` pieces on the grid with **at most** one piece per cell.
10+
11+
Since the answer may be very large, return it **modulo** <code>10<sup>9</sup> + 7</code>.
12+
13+
The Manhattan Distance between two cells <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and <code>(x<sub>j</sub>, y<sub>j</sub>)</code> is <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>.
14+
15+
**Example 1:**
16+
17+
**Input:** m = 2, n = 2, k = 2
18+
19+
**Output:** 8
20+
21+
**Explanation:**
22+
23+
The valid arrangements of pieces on the board are:
24+
25+
![](https://assets.leetcode.com/uploads/2024/12/25/4040example1.drawio)![](https://assets.leetcode.com/uploads/2024/12/25/untitled-diagramdrawio.png)
26+
27+
* In the first 4 arrangements, the Manhattan distance between the two pieces is 1.
28+
* In the last 2 arrangements, the Manhattan distance between the two pieces is 2.
29+
30+
Thus, the total Manhattan distance across all valid arrangements is `1 + 1 + 1 + 1 + 2 + 2 = 8`.
31+
32+
**Example 2:**
33+
34+
**Input:** m = 1, n = 4, k = 3
35+
36+
**Output:** 20
37+
38+
**Explanation:**
39+
40+
The valid arrangements of pieces on the board are:
41+
42+
![](https://assets.leetcode.com/uploads/2024/12/25/4040example2drawio.png)
43+
44+
* The first and last arrangements have a total Manhattan distance of `1 + 1 + 2 = 4`.
45+
* The middle two arrangements have a total Manhattan distance of `1 + 2 + 3 = 6`.
46+
47+
The total Manhattan distance between all pairs of pieces across all arrangements is `4 + 6 + 6 + 4 = 20`.
48+
49+
**Constraints:**
50+
51+
* <code>1 <= m, n <= 10<sup>5</sup></code>
52+
* <code>2 <= m * n <= 10<sup>5</sup></code>
53+
* `2 <= k <= m * n`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package g3401_3500.s3423_maximum_difference_between_adjacent_elements_in_a_circular_array;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void maxAdjacentDistance() {
11+
assertThat(new Solution().maxAdjacentDistance(new int[] {1, 2, 4}), equalTo(3));
12+
}
13+
14+
@Test
15+
void maxAdjacentDistance2() {
16+
assertThat(new Solution().maxAdjacentDistance(new int[] {-5, -10, -5}), equalTo(5));
17+
}
18+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package g3401_3500.s3424_minimum_cost_to_make_arrays_identical;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void minCost() {
11+
assertThat(
12+
new Solution().minCost(new int[] {-7, 9, 5}, new int[] {7, -2, -5}, 2),
13+
equalTo(13L));
14+
}
15+
16+
@Test
17+
void minCost2() {
18+
assertThat(new Solution().minCost(new int[] {2, 1}, new int[] {2, 1}, 0), equalTo(0L));
19+
}
20+
}

0 commit comments

Comments
 (0)