[lintcode]741. Calculate Maximum Value II

链接:http://www.lintcode.com/zh-cn/problem/calculate-maximum-value-ii/


Given a string of numbers, write a function to find the maximum value from the string, you can add a + or * sign between any two numbers,It's different with Calculate Maximum Value, You can insert parentheses anywhere.


Given str = 01231, return 12
(0 + 1 + 2) * (3 + 1) = 12 we get the maximum value 12

Given str = 891, return 80
As 8 * (9 + 1) = 80, so 80 is maximum.


class Solution {
public:
    /**
     * @param str: a string of numbers
     * @return: the maximum value
     */
    int maxValue(string &str) {
        // write your code here
        int size=str.size();
        if(size==0)
            return 0;
        vector<int> nums;
        for(auto c: str)
            nums.push_back(c-'0');
        vector<vector<int>> dp(size,vector<int>(size,0));
        for(int i=0;i<size;i++)
        {
            dp[i][i]=nums[i];
        }
        for(int step=1;step<size;step++)
        {
            for(int left=0;left<size-step;left++)
            {
                int right=left+step;
                int maxvalue=0;
                for(int mid=left;mid<right;mid++)
                {
                    maxvalue=max(maxvalue,max(dp[left][mid]+dp[mid+1][right],dp[left][mid]*dp[mid+1][right]));
                }
                dp[left][right]=maxvalue;
            }
        }
        return dp[0][size-1];
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值