解题思路

  1. 这是一个整数分解问题,需要找到使乘积最大的分解方式
  2. 通过数学分析可以得出以下规律:
    • 时,最大乘积就是数字本身
    • 时,应尽可能多地分解出
    • 最后剩余的数如果是 ,应该和前面的 合并成
  3. 可以使用递归或迭代的方式实现

代码

#include <iostream>
using namespace std;

int getMaxProduct(int n) {
    switch(n) {
        case 1: return 1;
        case 2: return 2;
        case 3: return 3;
        case 4: return 4;
        case 5: return 6;  // 2*3
        case 6: return 9;  // 3*3
        default: return 3 * getMaxProduct(n-3);  // 分解出一个3
    }
}

int main() {
    int n;
    while(cin >> n) {
        cout << getMaxProduct(n) << endl;
    }
    return 0;
}
import java.util.Scanner;

public class Main {
    public static int getMaxProduct(int n) {
        switch(n) {
            case 1: return 1;
            case 2: return 2;
            case 3: return 3;
            case 4: return 4;
            case 5: return 6;  // 2*3
            case 6: return 9;  // 3*3
            default: return 3 * getMaxProduct(n-3);  // 分解出一个3
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int n = sc.nextInt();
            System.out.println(getMaxProduct(n));
        }
    }
}
def get_max_product(n):
    if n == 1: return 1
    if n == 2: return 2
    if n == 3: return 3
    if n == 4: return 4
    if n == 5: return 6  # 2*3
    if n == 6: return 9  # 3*3
    return 3 * get_max_product(n-3)  # 分解出一个3

while True:
    try:
        n = int(input())
        print(get_max_product(n))
    except EOFError:
        break

算法及复杂度

  • 算法:递归/数学
  • 时间复杂度: - 每次递归减少 3
  • 空间复杂度: - 递归调用栈的深度