From c228a24b1afad10c6703dc888b02da4d4f199b23 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 17 Mar 2024 23:39:17 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB525.=20Contiguous=20Array?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/contiguous-array.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 cpp/contiguous-array.cpp 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; + } +};