LeetCode343

来源:互联网 发布:socket 的类型 知乎 编辑:程序博客网 时间:2024/05/19 19:59

EX.343

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 36 (10 = 3 + 3 + 4).

Note: You may assume that n is not less than 2 and not larger than 58.

Solution:

题意分析,始终返回和为给定值的最大乘积
假定给定值为n,最大乘积为max

n = 2, max = 1*1;
n = 3, max = 2*1;
n = 4, max = 2*2;
n = 5, max = 3*2;
n = 6, max = 3*3;
n = 7, max = 3*4;
n = 8, max = 3*3*2;
n = 9, max = 3*3*3;
n = 10, max = 3*3*4;
……
max = 3*3*3…….*2 || 3*3*3……*3 || 3*3*3……*4

class Solution {public:    int integerBreak(int n) {        switch(n) {            case 2:                return 1;                break;            case 3:                return 2;                break;            case 4:                return 4;                break;        }        int count = n/3;        int temp = n%3;        if (temp == 1) {            return 4*getNum(count-1);        } else if(temp == 0) {            return getNum(count);        } else {            return 2*getNum(count);        }    }    int getNum(int count) {        int res = 1;        for(int i = 0; i < count; i++) {            res *= 3;        }        return res;    }};