leetcode343

public class Solution {
    public int IntegerBreak(int n) {
        if (n == 2)
            {
                return 1;
            }
            else if (n == 3)
            {
                return 2;
            }
            var max = int.MinValue;
            for (int i = 2; i <= n / 2; i++)
            {
                var div = n / i;
                var mod = n % i;
                var cur = 0;
                if (mod == 0)
                {
                    cur = Convert.ToInt32(Math.Pow(i, div));
                }
                else
                {
                    var cur1 = Convert.ToInt32(Math.Pow(i, div - 1) * (i + mod));
                    var cur2 = Convert.ToInt32(Math.Pow(i, div)) * mod;
                    cur = Math.Max(cur1, cur2);
                }
                if (cur > max)
                {
                    max = cur;
                }
                else
                {
                    break;
                }
            }
            return max;
    }
}

https://leetcode.com/problems/integer-break/#/description

时间: 2024-10-25 14:53:11

leetcode343的相关文章

LeetCode-343. 整数拆分

题目描述 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化. 返回你可以获得的最大乘积. 例如,给定 n = 2,返回1(2 = 1 + 1):给定 n = 10,返回36(10 = 3 + 3 + 4). 注意:你可以假设 n 不小于2且不大于58. 感谢: 特别感谢 @jianchao.li.fighter 添加此问题并创建所有测试用例. 思路 递归求解 首先将原问题拆分成可递归的子问题,如果mem[n]表示正整数n的最大成绩,则递归方程就是mem[n] = max

LeetCode 343

Integer Break Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return