From 26d202b4c5c5e00888613ba08d0eee945225ee16 Mon Sep 17 00:00:00 2001 From: aucker Date: Fri, 14 Jun 2024 09:13:14 +0800 Subject: [PATCH] June14: DP state transition w/ fixed size array Time: O(N), Space: O(1), DP practice --- daily/June14.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 daily/June14.cpp diff --git a/daily/June14.cpp b/daily/June14.cpp new file mode 100644 index 0000000..b7cba77 --- /dev/null +++ b/daily/June14.cpp @@ -0,0 +1,43 @@ +#include + +#include +using namespace std; + +class Solution { + public: + /** + * @brief LC: 2786: Visit Array positions to max score + * This is a DP problem, with optimized solution + * Time: O(N), Space: O(1) + * a vector w/ fixed size like 2 is Space complexity of O(1) + * But a vector space complexity is usually O(N) + * + * @param nums + * @param x + * @return long long + */ + long long maxScore(vector& nums, int x) { + // vector dp = {INT_MIN, INT_MIN}; + vector dp(2, numeric_limits::min()); + dp[nums[0] % 2] = nums[0]; + for (int i = 1; i < nums.size(); i++) { + int state = nums[i] % 2; + dp[state] = max(dp[state] + nums[i], dp[abs(state - 1)] + nums[i] - x); + } + return max(dp[0], dp[1]); + } + + // long long maxScoreOP(vector& nums, int x) { + // bool isEven = nums[0] % 2 == 0; + // long long oddMax = 0, evenMax = 0; + // if (isEven) evenMax = nums[0]; + // else oddMax = nums[0]; + + // for (size_t i = 1; i < nums.size(); i++) { + // isEven = nums[i] % 2 == 0; + // if (isEven) evenMax = max(evenMax + nums[i], oddMax + nums[i] - x); + // else oddMax = max(oddMax + nums[i], evenMax + nums[i] - x); + // } + // return max(oddMax, evenMax); + // } +}; \ No newline at end of file