【Lintcode】719. Calculate Maximum Value

题目地址:

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 a2并且 x ≤ 1 x\le 1 x1的时候也成立,其余情况都应该做乘法。所以结论就是,当 a ≤ 1 a\le 1 a1或者 x ≤ 1 x\le 1 x1的时候做加法,否则做乘法。代码如下:

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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值