中级农民
- 积分
- 138
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-9-7
- 最后登录
- 1970-1-1
|
The idea is similar to LC282. However, this problem has no target value. Let dp[i] note the max value we could get from partial array of first several consecutive entries. Then the key is to check where should we insert the last "+" or not to use "+" at all (i.e., insert "*" for all positions).- int getPlusMultiplyMax(vector<int>& a) {
- int n = a.size();
- if (n == 0) return INT_MIN; // default answer for empty array
- // dp[i]: max value generated from a[0],...,a[i]
- vector<int> dp(n); dp[0] = a[0];
- for (int i = 1; i < n; ++i) dp[i] = a[i]*dp[i-1];
- for (int i = 1; i < n; ++i) {
- int lastProduct = 1;
- for (int j = i-1; j >= 0; j--) {
- lastProduct *= a[j+1];
- dp[i] = max(dp[j], dp[j] + lastProduct);
- }
- }
- return dp[n-1];
- }
复制代码
补充内容 (2016-10-10 07:29):
Actually, I think this problem is easier than LC282 since we don't need to worry about matching target value or special treatment for "*" which is precedent to "+" operator in calculation. |
|