From e3b069be8c04371e44e2d871dac8ed51aa2a6aad Mon Sep 17 00:00:00 2001 From: Jeffrey Hsu Date: Thu, 17 Jul 2025 17:19:52 +0800 Subject: [PATCH] 3201 --- include/solution/3201.h | 11 +++++++++++ src/3201.c | 13 +++++++++++++ tests/test_3201.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 include/solution/3201.h create mode 100644 src/3201.c create mode 100644 tests/test_3201.cpp diff --git a/include/solution/3201.h b/include/solution/3201.h new file mode 100644 index 0000000..8bb4d8b --- /dev/null +++ b/include/solution/3201.h @@ -0,0 +1,11 @@ +#ifndef INC_3201_H +#define INC_3201_H +#ifdef __cplusplus +extern "C" +{ +#endif + int maximumLength(int *nums, int numsSize); +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/src/3201.c b/src/3201.c new file mode 100644 index 0000000..acaf616 --- /dev/null +++ b/src/3201.c @@ -0,0 +1,13 @@ +#include + +#define max(x, y) ((x) > (y) ? (x) : (y)) + +int maximumLength(int *nums, int numsSize) +{ + int odd = 0, even = 0, odd_cnt = 0; + + for (int i = 0; i < numsSize; i++) + nums[i] & 1 ? (odd = even + 1, odd_cnt++) : (even = odd + 1); + + return max(max(even, odd), max(odd_cnt, numsSize - odd_cnt)); +} \ No newline at end of file diff --git a/tests/test_3201.cpp b/tests/test_3201.cpp new file mode 100644 index 0000000..16b3536 --- /dev/null +++ b/tests/test_3201.cpp @@ -0,0 +1,38 @@ +#include +#include + +class MaximumLengthTest : public ::testing::Test +{ + protected: + // 提供统一断言接口 + void AssertMaximumLength(const std::vector &input, int expected) + { + int *arr = const_cast(input.data()); + int result = maximumLength(arr, input.size()); + EXPECT_EQ(result, expected); + } +}; + +// 示例 1:输入 [1,2,3,4],输出 4 +TEST_F(MaximumLengthTest, IncreasingSequence) +{ + AssertMaximumLength({1, 2, 3, 4}, 4); +} + +// 示例 2:输入 [1,2,1,1,2,1,2],输出 6 +TEST_F(MaximumLengthTest, AlternatingSequence) +{ + AssertMaximumLength({1, 2, 1, 1, 2, 1, 2}, 6); +} + +// 示例 3:输入 [1,3],输出 2 +TEST_F(MaximumLengthTest, ShortSequence) +{ + AssertMaximumLength({1, 3}, 2); +} + +// 示例 4:输入 [4,51,68],输出 3 +TEST_F(MaximumLengthTest, TEST4) +{ + AssertMaximumLength({4, 51, 68}, 3); +} \ No newline at end of file