小于n的最大数Java

给定一个数字字符串S和一个数组nums,数组中的元素都在0~9之间,问从数组中选择元素组成的数字,小于N的最大值是多少?

例如:S = “24378”,nums:{2,3,9},组成的最大值为23999。

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int[] nums = new int[]{9, 3, 2, 4, 8};
        nums = new int[]{9};

        int[] N = new int[]{2, 4, 3, 8, 9};
        System.out.println(getMaxLessNum(nums, N));

    }

    public static String getMaxLessNum(int[] nums, int[] n) {
        Arrays.sort(nums);


        StringBuilder s = new StringBuilder();
        System.out.println(dfs(true, s, nums, n, 0));


        return s.toString();
    }

    private static boolean dfs(boolean equal, StringBuilder s, int[] nums, int[] n, int index) {
    //如果是最后一位,则需要判定是否有小于n的数
        if (index == n.length - 1) {
            if (!equal) {
                s.append(nums[nums.length - 1]);
                return true;
            } else {
                for (int i = nums.length - 1; i >= 0; i--) {
                    if (nums[i] < n[n.length - 1]) {
                        s.append(nums[i]);
                        return true;
                    }
                }
                return false;
            }
        }

        //前面有不相等的,后面都取nums的最大值即可
        if (!equal) {
            for (int i = index; i < n.length; i++) {
                s.append(nums[nums.length - 1]);
            }
            return true;
        }

        //前面都相等,优先取和n[i]相同的值,深度优先遍历,如果后面组成的数小于n,则找到了最大的值。如果当前值小于n[i],则后面都取nums的最大值即可
        for (int i = nums.length - 1; i >= 0; i--) {
            if (nums[i] == n[index]) {
                s.append(nums[i]);
                boolean result = dfs(true, s, nums, n, index + 1);
                if (result) {
                    return true;
                } else {
                    s.deleteCharAt(s.length() - 1);
                }
            }

            if (nums[i] < n[index]) {
                s.append(nums[i]);
                dfs(false, s, nums, n, index + 1);
                return true;
            }
        }

        //如果前面都不满足,删除第一位即可
        if (index == 0) {
            dfs(false, s, nums, n, index + 1);
            return true;
        }


        return false;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值