Skip to content

Commit b8ef217

Browse files
authored
Create 525. Contiguous Array (#430)
2 parents 5fc79a4 + c3cc2f6 commit b8ef217

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

525. Contiguous Array

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <vector>
2+
#include <unordered_map>
3+
#include <algorithm>
4+
5+
class Solution {
6+
public:
7+
int findMaxLength(std::vector<int>& nums) {
8+
std::unordered_map<int, int> sumMap;
9+
int maxLength = 0;
10+
int sum = 0;
11+
12+
sumMap[0] = -1; // Initialize with 0 sum at index -1
13+
14+
for (int i = 0; i < nums.size(); ++i) {
15+
// Increment sum for 1, decrement for 0
16+
sum += (nums[i] == 1) ? 1 : -1;
17+
18+
19+
if (sumMap.find(sum) != sumMap.end()) {
20+
maxLength = std::max(maxLength, i - sumMap[sum]);
21+
} else {
22+
sumMap[sum] = i; // Store the index of first occurrence of sum
23+
}
24+
}
25+
26+
return maxLength;
27+
}
28+
};

0 commit comments

Comments
 (0)