剑指OFFER----面试题14- I. 剪绳子

时间:2021-10-02 21:45:54

链接:https://leetcode-cn.com/problems/jian-sheng-zi-lcof/

思路:

  1.假设ni >= 5, 3 * (ni - 3) >= ni ? 3ni - 9 >= ni ? 2ni >= 9

  2.ni = 4, 4 = 2 * 2

  3.2 * 2 * 2 < 3 * 3

-----> 最多划分两个2,其他都是3.

代码:

class Solution {
public:
    int cuttingRope(int n) {
        if (n <= 3) return 1 * (n - 1);
        int res = 1;
        if (n % 3 == 1) res *= 4, n -= 4;
        if (n % 3 == 2) res *= 2, n -= 2;

        while (n) res *=3, n-=3;
        return res;
    }
};