Skip to content

Commit 12d26ff

Browse files
committed
Contiguous Array
1 parent 7591cf7 commit 12d26ff

File tree

3 files changed

+79
-1
lines changed

3 files changed

+79
-1
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package leetcode.medium;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class ContiguousArray {
7+
8+
int findMaxLength(int[] nums) {
9+
10+
if (nums == null || nums.length == 0) { // Base Case
11+
return 0;
12+
}
13+
14+
// Converting all 0 to -1
15+
for (int i = 0; i < nums.length; i++)
16+
if (nums[i] == 0) nums[i] = -1;
17+
18+
int sum = 0; // current
19+
int maxLength = 0; // final-ans
20+
21+
Map<Integer, Integer> map = new HashMap<>();
22+
map.put(0, -1); // put sentinel value
23+
24+
for (int i = 0; i < nums.length; i++) {
25+
sum += nums[i];
26+
27+
if (map.containsKey(sum)) {
28+
// if present, update length
29+
int last = map.get(sum);
30+
maxLength = Math.max(maxLength, i - last);
31+
} else
32+
map.put(sum, i);
33+
34+
}
35+
36+
return maxLength;
37+
}
38+
39+
}

src/main/java/leetcode/medium/MaximalSquare.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ int maximalSquare(char[][] matrix) {
1919
dp[i][j] = 1;
2020
else
2121
// For others, dp[i][j] is the minimum of the three neighbors
22-
dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
22+
dp[i][j] = 1 +
23+
Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]);
2324

2425
maxSide = Math.max(maxSide, dp[i][j]);
2526
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package leetcode.medium;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class ContiguousArrayTest {
8+
9+
private final ContiguousArray contiguousArray;
10+
11+
ContiguousArrayTest() {
12+
contiguousArray = new ContiguousArray();
13+
}
14+
15+
@Test
16+
void testFindMaxLength1() {
17+
int[] nums = {0, 1, 0, 1, 0, 1};
18+
assertEquals(6, contiguousArray.findMaxLength(nums));
19+
}
20+
21+
@Test
22+
void testFindMaxLength2() {
23+
int[] nums = {0};
24+
assertEquals(0, contiguousArray.findMaxLength(nums));
25+
}
26+
27+
@Test
28+
void testFindMaxLength3() {
29+
int[] nums = {0, 1};
30+
assertEquals(2, contiguousArray.findMaxLength(nums));
31+
}
32+
33+
@Test
34+
void testFindMaxLength4() {
35+
int[] nums = {0, 1, 1, 0, 1};
36+
assertEquals(4, contiguousArray.findMaxLength(nums));
37+
}
38+
}

0 commit comments

Comments
 (0)