Skip to content

Commit

Permalink
impl max product subarray
Browse files Browse the repository at this point in the history
  • Loading branch information
SKTT1Ryze committed Mar 6, 2024
1 parent 8bafaf7 commit 52ddbcb
Showing 1 changed file with 47 additions and 5 deletions.
52 changes: 47 additions & 5 deletions leetcode-cc/MaxProductSubarray.hpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#include <algorithm>

#include "TestHelper.h"
#include "problem.h"
#include "solution.h"
Expand All @@ -8,7 +10,7 @@ IMPLEMENT_PROBLEM_CLASS(PMaxProductSubarray, 152, DIFFI_MEDIUM,
TOPIC_ALGORITHMS, "Maximum Product Subarray",
"Given an integer array nums, find a subarray that has "
"the largest product, and return the product.",
{""});
{"DP"});

class SMaxProductSubarray : public ISolution {
public:
Expand All @@ -18,12 +20,52 @@ class SMaxProductSubarray : public ISolution {
}
string location() const override { return __FILE_NAME__; }
int test() const override {
return testHelper<vector<int>, int>(
{{2, 3, -2, 4}, {-2, 0, -1}}, {6, 0},
[this](auto input) { return this->maxProduct(input); });
return testHelper<vector<int>, int>({{2, 3, -2, 4}, {-2, 0, -1}}, {6, 0},
[this](auto input) {
// return this->maxProduct(input);
return this->maxProductV2(input);
});
};
int benchmark() const override { return 0; }

private:
int maxProduct(vector<int>& nums) const {}
// work, but time limit
int maxProduct(vector<int>& nums) const {
int n = nums.size();
vector<vector<int>> dp(n, vector(n, 0));
int res = INT_MIN;

for (int i = 0; i < n; i++) {
dp[i][i] = nums[i];
res = max(res, dp[i][i]);
}

for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
dp[i][j] = dp[i][j - 1] * nums[j];
res = max(res, dp[i][j]);
}
}

return res;
}

int maxProductV2(vector<int>& nums) const {
int n = nums.size();
if (n == 0) return 0;

int max_product = nums[0];
int min_product = nums[0];
int result = nums[0];

for (int i = 1; i < n; ++i) {
int temp_max = max_product;
int temp_min = min_product;
max_product = max({nums[i], nums[i] * temp_max, nums[i] * temp_min});
min_product = min({nums[i], nums[i] * temp_max, nums[i] * temp_min});
result = max(result, max_product);
}

return result;
}
};

0 comments on commit 52ddbcb

Please sign in to comment.