1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 01:36:57 +02:00

cpp: add «525. Contiguous Array»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-03-17 23:39:17 +01:00
parent 15bd5cb743
commit c228a24b1a
Signed by: mfocko
GPG key ID: 7C47D46246790496

27
cpp/contiguous-array.cpp Normal file
View file

@ -0,0 +1,27 @@
#include <unordered_map>
#include <vector>
class Solution {
public:
int findMaxLength(const std::vector<int> &nums) {
std::unordered_map<int, int> lengths;
lengths[0] = -1;
int max_length = 0;
int count = 0;
for (auto i = 0u; i < nums.size(); ++i) {
count += nums[i] == 1 ? 1 : -1;
auto len = lengths.find(count);
if (len != lengths.end()) {
max_length =
std::max(max_length, static_cast<int>(i) - len->second);
} else {
lengths[count] = i;
}
}
return max_length;
}
};