diff --git a/cpp/contiguous-array.cpp b/cpp/contiguous-array.cpp new file mode 100644 index 0000000..f6b11d3 --- /dev/null +++ b/cpp/contiguous-array.cpp @@ -0,0 +1,27 @@ +#include +#include + +class Solution { + public: + int findMaxLength(const std::vector &nums) { + std::unordered_map 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(i) - len->second); + } else { + lengths[count] = i; + } + } + + return max_length; + } +};