题目地址:
https://www.lintcode.com/problem/719/
给定一个长 n n n的只含数字的字符串 s s s,给定一个初始值 0 0 0,接下来扫描这个字符串,每次遇到某个数字的时候可以决定是加上它还是乘以它。求最终结果的最大可能值。
考虑非负整数 x x x, x + a > a x x+a>ax x+a>ax在 a = 0 a=0 a=0或者 a = 1 a=1 a=1的时候成立,当 a ≥ 2 a\ge 2 a≥2并且 x ≤ 1 x\le 1 x≤1的时候也成立,其余情况都应该做乘法。所以结论就是,当 a ≤ 1 a\le 1 a≤1或者 x ≤ 1 x\le 1 x≤1的时候做加法,否则做乘法。代码如下:
public class Solution {
/**
* @param str: the given string
* @return: the maximum value
*/
public int calcMaxValue(String str) {
// write your code here
int res = 0;
for (int i = 0; i < str.length(); i++) {
int x = str.charAt(i) - '0';
if (x <= 1 || res <= 1) {
res += x;
} else {
res *= x;
}
}
return res;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。