Skip to content

Commit 12e5401

Browse files
committed
Add the solution for LC #3698
1 parent cc5a5b2 commit 12e5401

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package org.sean.array;
2+
3+
/***
4+
* 3698. Split Array With Minimum Difference
5+
*/
6+
public class SubArrayMinDiffer {
7+
8+
public long splitArray(int[] nums) {
9+
// two pointers
10+
// left -> <- right
11+
// |
12+
// | | |
13+
// | | | ...| |
14+
//
15+
int n = nums.length;
16+
int left = 0, right = n - 1;
17+
long sumLeft = 0, sumRight = 0;
18+
19+
sumLeft += nums[left];
20+
sumRight += nums[right];
21+
22+
long res = Long.MAX_VALUE;
23+
while (left + 1 < right) {
24+
if (nums[left + 1] > nums[left]) {
25+
sumLeft += nums[left + 1];
26+
left++;
27+
} else {
28+
break;
29+
}
30+
}
31+
32+
// move the right ptr
33+
while (right - 1 > left) {
34+
if (nums[right - 1] > nums[right]) {
35+
sumRight += nums[right - 1];
36+
right--;
37+
} else {
38+
break;
39+
}
40+
}
41+
42+
//System.out.printf(">>> left: %d, right: %d\n", left, right);
43+
if (left + 1 == right) {
44+
res = Math.min(Math.abs(sumLeft - sumRight), res);
45+
} else {
46+
return -1;
47+
}
48+
49+
while (left > 0) {
50+
if (nums[left] > nums[right]) {
51+
sumRight += nums[left];
52+
sumLeft -= nums[left];
53+
54+
res = Math.min(Math.abs(sumLeft - sumRight), res);
55+
left--;
56+
right--;
57+
} else {
58+
break;
59+
}
60+
}
61+
62+
return res;
63+
}
64+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package org.sean.array;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.*;
7+
8+
public class SubArrayMinDifferTest {
9+
10+
private SubArrayMinDiffer minDiffer;
11+
12+
@Before
13+
public void setUp() throws Exception {
14+
minDiffer = new SubArrayMinDiffer();
15+
}
16+
17+
@Test
18+
public void splitArray() {
19+
assertEquals(5L, minDiffer.splitArray(new int[]{
20+
1, 2, 3, 5, 4, 2
21+
}));
22+
}
23+
24+
@Test
25+
public void splitInvalidArray() {
26+
assertEquals(-1L, minDiffer.splitArray(new int[]{3, 1, 2}));
27+
}
28+
}

0 commit comments

Comments
 (0)