Calculate Maximum Value II -LintCode
2018-01-26 11:16
204 查看
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.
思路:
构建数组res[][],res[i][j]表示从str[i]到str[j]的字符串,可以取得的最大值。
在不同步长的情况下,计算不同位置的值:对于01231
如先计算[0,1],[1,2],[2,3]… 再计算[0,1,2],[1,2,3]…
递归求解在位置为i,步长为path的情况下,由字符串可以取得的最大值,并将其赋值给res[i][i+path-1]。
样例
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.
思路:
构建数组res[][],res[i][j]表示从str[i]到str[j]的字符串,可以取得的最大值。
在不同步长的情况下,计算不同位置的值:对于01231
如先计算[0,1],[1,2],[2,3]… 再计算[0,1,2],[1,2,3]…
递归求解在位置为i,步长为path的情况下,由字符串可以取得的最大值,并将其赋值给res[i][i+path-1]。
#ifndef C741_H #define C741_H #include<iostream> #include<string> #include<vector> using namespace std; class Solution { public: /** * @param str: a string of numbers * @return: the maximum value */ int maxValue(string &str) { // write your code here if (str.empty()) return 0; int len = str.size(); vector<vector<int>> res(len, vector<int>(len, INT_MIN));//res[i][j]存放从str[i]到str[j]的最大值 for (int i = 0; i<len; ++i)//初始化res res[i][i] = str[i] - '0'; //在不同步长不同位置的情况下计算res的值 for (int path = 2; path <= len; ++path) { for (int i = 0; i + path <= len;++i) res[i][i + path - 1] = ComputeMax(i, path, res); } return res[0][len - 1]; } //递归计算位置i,步长为path的情况下取得的最大值 int ComputeMax(int i,int path,vector<vector<int>> vec) { int res = INT_MIN; if (vec[i][i + path - 1] != INT_MIN) return vec[i][i + path - 1]; for (int k = 1; k < path; ++k) { int left = ComputeMax(i, k, vec); int right = ComputeMax(i + k, path - k, vec); res = maxVal(maxVal(left + right, left*right),res); } return res; } int maxVal(int a, int b) { return a > b ? a : b; } }; #endif
相关文章推荐
- Calculate Maximum Value II
- [Lintcode]Maximum Subarray II 最大子数组 II
- 1. MaxCounters 计数器 Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.
- LintCode-Maximum Subarray II
- [lintcode] Binary Tree Maximum Path Sum II
- [lintcode] Binary Tree Maximum Path Sum II
- Lintcode - Maximum Subarray II
- Lintcode: Maximum Subarray II
- Lintcode 螺旋矩阵 II
- LintCode 34 N皇后问题 II
- LintCode 63 搜索旋转排序数组 II
- lintcode-medium-N Queens II
- [lintcode]108. 分割回文串 II
- [LintCode] Trapping rain water II
- MySQL how to calculate average value of max/min N records by group
- [Lintcode]Maximum Product Subarray乘积最大子序列
- LintCode-整数排序 II
- [LintCode] Paint House II 粉刷房子之二
- lintcode 中等题:Singleton number II 落单的数 II
- 摆动排序 II-LintCode