您的位置:首页 > 其它

LeetCode "Maximum Product Subarray"

2014-10-11 07:41 393 查看
Intuitively there must a O(n) solution.

First I tried a bottom-up DP solution but it had a TLE:

class Solution {
public:
int maxProduct(int A[], int n) {
vector<int> dp;dp.resize(n);
dp.assign(A, A + n);

int max = *std::max_element(A, A + n);
for (size_t len = 2; len <= n; len ++)
for (int i = 0; i <= n - len; i ++)
{
dp[i] *= A[i + len - 1];
max = std::max(max, dp[i]);
}

return max;
}
};


So what is O(n) solution then? The idea is to keep track of 2 lines: one for positive and one for negative. Inspired by:
https://oj.leetcode.com/discuss/11923/sharing-my-solution-o-1-space-o-n-running-time
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: