LeetCode:Math

本文探讨了整数拆分问题的最佳解决方案,通过分析得出最优拆分方案为尽可能多地使用数字3进行组合,并提供了特殊情况处理策略。此外,还深入研究了自我交叉判断问题,通过四种不同情况的分析,提出了一种简洁高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4.Math

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

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

利用求导来分析,分析结果得到大部分情况应该按3切分,如果n>=5,那么果断都应该按3切分,如果n<5,作为特殊情况来考虑(比如4就应该拆分成2*2,而不是3*1)。

public class Solution {
    public int integerBreak(int n) {
        //特殊情况
        if(n==2){
            return 1;
        }
        if(n==3){
            return 2;
        }
        int product=1;
        while(n>=5){
            product = product*3;
            n=n-3;
        }
        product = product*n;
        return product;
    }
}

2.Self Crossing

题目

参考Java Oms with explanation实现:

public class Solution {
    /*               i-2
    case 1 : i-1┌─┐
                └─┼─>i
                 i-3

                    i-2
    case 2 : i-1 ┌────┐
                 └─══>┘i-3
                 i  i-4      (i overlapped i-4)

    case 3 :    i-4
               ┌──┐
               │i<┼─┐
            i-3│ i-5│i-1
               └────┘
                i-2

*/
    //只有上述四种情况之一
    public boolean isSelfCrossing(int[] num) {
        int length = num.length;
        if(length<=3){
            return false;
        }
        for (int i = 3; i < length; i++) {
            //case 1
            if(num[i-1]<=num[i-3]&&num[i]>=num[i-2]){
                return true;
            }
            //case 2
            if(i>=4){
                if(num[i-1]==num[i-3]&&num[i]+num[i-4]>=num[i-2]){
                    return true;
                }
            }
            //case 3
            if(i>=5){
                if(num[i]+num[i-4]>=num[i-2]&&num[i-1]+num[i-5]>=num[i-3]&&num[i-1]<=num[i-3]&&num[i-2]>num[i-4]){
                    return true;
                }
            }

        }
        return false;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值