1363. Largest Multiple of Three (H)

本文介绍了一种算法,用于从给定的整数数组中找出能组成的最大且为3的倍数的多位数。通过分析数字之和与3的关系,采用哈希表记录数字频率,进而调整组合以满足条件。

Largest Multiple of Three (H)

Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.

Since the answer may not fit in an integer data type, return the answer as a string.

If there is no answer return an empty string.

Example 1:

Input: digits = [8,1,9]
Output: "981"

Example 2:

Input: digits = [8,6,7,1,0]
Output: "8760"

Example 3:

Input: digits = [1]
Output: ""

Example 4:

Input: digits = [0,0,0,0,0,0]
Output: "0"

Constraints:

  • 1 <= digits.length <= 10^4
  • 0 <= digits[i] <= 9
  • The returning answer must not contain unnecessary leading zeros.

题意

给定一个只包含个位数的数组,将其组合成一个最大的多位数字符串,使这个多位数是3的倍数。

思路

首先需要知道一条性质:如果一个多位数的各位数字之和是3的倍数,那么这个多位数一定是3的倍数(充要条件)。很好证明:
( a b c d e ) 10 = a ∗ 10000 + b ∗ 1000 + c ∗ 100 + d ∗ 10 + e = ( a + b + c + d + e ) + a ∗ 9999 + b ∗ 999 + c ∗ 99 + d ∗ 9 (abcde)_{10} = a*10000+b*1000+c*100+d*10+e=(a+b+c+d+e)+a*9999+b*999+c*99+d*9 (abcde)10=a10000+b1000+c100+d10+e=(a+b+c+d+e)+a9999+b999+c99+d9
从公式可以看出只要 a+b+c+d+e 是3的倍数,(abcde)一定是3的倍数;同样,如果(abcde)是3的倍数,那么 a+b+c+d+e也一定是3的倍数。

在这个性质的基础上,我们用一张hash表记录所有数字出现的次数,并计算出总和sum,会有3种情况:

  1. sum % 3 == 0。说明用所有数字组合成的多位数一定是3的倍数;
  2. sum % 3 == 1。说明需要去掉一个模3为1的数,或者去掉两个模3为2的数;
  3. sum % 3 == 2。说明需要去掉一个模3为2的数,或者去掉两个模3为1的数。

进行完上述操作后,将hash表中剩余的所有数字组合起来就是要求的答案。


代码实现

class Solution {
    public String largestMultipleOfThree(int[] digits) {
        int[] hash = new int[10];
        int sum = 0;
        int remain1 = 0, remain2 = 0;
        String ans = null;
        
        // 遍历生成hash表并求和
        for (int i = 0; i < digits.length; i++) {
            sum += digits[i];
            hash[digits[i]]++;
        }
        remain1 = hash[1] + hash[4] + hash[7];		// 模3余1的数的个数
        remain2 = hash[2] + hash[5] + hash[8];		// 模3余2的数的个数
        
        // 分情况处理
        if (sum % 3 == 1) {
            if (remain1 >= 1) {
                for (int i = 1; i <= 7; i += 3) {
                    if (hash[i] >= 1) {
                        hash[i]--;
                        break;
                    }
                }
            } else {
                int count = 0;
                for (int i = 2; i <= 8; i += 3) {
                    while (hash[i] != 0 && count != 2) {
                        hash[i]--;
                        count++;
                    }
                }
            }
        } else if (sum % 3 == 2) {
            if (remain2 >= 1) {
                for (int i = 2; i <= 8; i += 3) {
                    if (hash[i] >= 1) {
                        hash[i]--;
                        break;
                    }
                }
            } else {
                for (int i = 1; i <= 7; i += 3) {
                    int count = 0;
                    while (hash[i] != 0 && count != 2) {
                        hash[i]--;
                        count++;
                    }
                }
            }
        }

        return generate(hash);
    }

    private String generate(int[] hash) {
        StringBuilder sb = new StringBuilder();
        for (int i = 9; i >= 1; i--) {
            for (int j = 0; j < hash[i]; j++) {
                sb.append(i);
            }
        }
        for (int i = 0; i < hash[0]; i++) {
            sb.append(0);
            if (sb.length() == 1) {
                break;
            }
        }
        return sb.toString();
    }
}

代码实现 - 简化版

// 简化版不求和,只对余数进行操作
class Solution {
    public String largestMultipleOfThree(int[] digits) {
        int[] hash = new int[10];
        int remain1 = 0, remain2 = 0;
        for (int i = 0; i < digits.length; i++) {
            hash[digits[i]]++;
        }
        remain1 = hash[1] + hash[4] + hash[7];
        remain2 = hash[2] + hash[5] + hash[8];
        
        int remainder = (remain1 + 2 * remain2) % 3;
        if (remainder == 1) {
            if (remain1 > 0) remain1--;
            else remain2 -= 2;
        } else if (remainder == 2) {
            if (remain2 > 0) remain2--;
            else remain1 -= 2;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 9; i >= 1; i--) {
            if (i % 3 == 0) {
                while (hash[i]-- > 0) sb.append(i);
            } else if (i % 3 == 1) {
                while (hash[i]-- > 0 && remain1-- > 0) sb.append(i);
            } else {
                while (hash[i]-- > 0 && remain2-- > 0) sb.append(i);
            }
        }
        while (hash[0]-- > 0) {
            sb.append(0);
            if (sb.length() == 1) break;
        }
        
        return sb.toString();
    }
}

参考

[Java] Basic Multiple of 3 - Clean code - O(N) ~ 2ms

Cut or not to cut, it is a question. In Fruit Ninja, comprising three or more fruit in one cut gains extra bonuses. This kind of cuts are called bonus cuts. Also, performing the bonus cuts in a short time are considered continual, iff. when all the bonus cuts are sorted, the time difference between every adjacent cuts is no more than a given period length of W. As a fruit master, you have predicted the times of potential bonus cuts though the whole game. Now, your task is to determine how to cut the fruits in order to gain the most bonuses, namely, the largest number of continual bonus cuts. Obviously, each fruit is allowed to cut at most once. i.e. After previous cut, a fruit will be regarded as invisible and won't be cut any more. In addition, you must cut all the fruit altogether in one potential cut. i.e. If your potential cut contains 6 fruits, 2 of which have been cut previously, the 4 left fruits have to be cut altogether. There are multiple test cases. The first line contains an integer, the number of test cases. In each test case, there are three integer in the first line: N(N<=30), the number of predicted cuts, M(M<=200), the number of fruits, W(W<=100), the time window. N lines follows. In each line, the first integer Ci(Ci<=10) indicates the number of fruits in the i-th cuts. The second integer Ti(Ti<=2000) indicate the time of this cut. It is guaranteed that every time is unique among all the cuts. Then follow Ci numbers, ranging from 0 to M-1, representing the identifier of each fruit. If two identifiers in different cuts are the same, it means they represent the same fruit. For each test case, the first line contains one integer A, the largest number of continual bonus cuts. In the second line, there are A integers, K1, K2, ..., K_A, ranging from 1 to N, indicating the (Ki)-th cuts are included in the answer. The integers are in ascending order and each separated by one space. If there are multiple best solutions, any one is accepted. 输入样例 1 4 10 4 3 1 1 2 3 4 3 3 4 6 5 3 7 7 8 9 3 5 9 5 4 输出样例 3 1 2 3
12-27
Let's start with some simple dynamic programming solution. As we go through the friends left to right, what is important for us to continue? It is how many elements we've chosen i , their sum s , their maximum m , and the current happiness of Little A h . As usual, of these four numbers, three have to be the DP parameters, and one has to be the DP result. The most natural choice is dp[i][s][m] -> max h. The transitions are trivial: loop through bi+1 , and update dp[i + 1] accordingly. This is O(nk3) solution which is quite slow. We need to add two optimizations. The first one is to get rid of the n factor. This is quite easy: if you want to use bi=x at some point, you'd put is as early as possible, i.e. at the first i where ai≥x . This means that from the whole array a we only need the prefix maxima, which leaves us with an array of length at most k . The second optimization is to get rid of linear transitions. Instead, we can do the backward-looking dp, and compute dp[i][s][m] as max(dp[i - 1][s][m], dp[i - 1][s - m][t]), where t is arbitrary. To choose this maximum, no loop is needed, as we can precompute this for every s−m . The final complexity is O(n+k3) .time limit per test2 seconds memory limit per test512 megabytes    It is said that writing wishing cards on New Year's Eve can bring good luck. You have written wishing cards and plan to give them to Little A. You have invited n friends to help you deliver the wishing cards. You plan to give the i -th friend bi wishing cards. The friends will visit Little A's house in the order of 1 to n , and each will hand over all his bi wishing cards to Little A. Little A always remembers the friend who gives her the most wishing cards, so after the j -th friend's visit, she gains happiness equal to the largest number of cards received so far, that is, max(b1,b2,…,bj) . The i -th friend can carry at most ai cards, and the total number of cards cannot exceed k . Your task is to optimally choose values of bi so that the total happiness of Little A after n visits is maximized under these constraints. Note that some friends may carry no cards at all, Little A won't get mad. DeepL 翻译    据说在除夕夜写许愿卡能带来好运。您已经写好了许愿卡,打算送给小 A。 您邀请了 n 个朋友帮您送许愿卡。您计划送给 i /位朋友 bi 张许愿卡。小 A 总是记得给她许愿卡最多的那个朋友,所以在第 j 个朋友到访后,她获得的快乐等于目前收到的最多的许愿卡,即 max(b1,b2,…,bj) 。 第 i 个朋友最多可以携带 ai 张卡片,卡片总数不能超过 k 。你的任务是优化选择 bi 的值,使小 A 在 n 次访问后的总快乐度在这些限制条件下达到最大。 注意,有些朋友可能根本不带卡片,小 A 也不会生气。    Input Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤103 ). The description of the test cases follows. The first line of each test case contains two integers n and k (1≤n≤105 , 1≤k≤360 ), the number of friends, and the maximum total number of cards. The second line of each test case contains n integers a1,a2,…,an (0≤ai≤k ), the maximum number of cards each friend can carry. It is guaranteed that the sum of n over all test cases does not exceed 5⋅105 and the sum of k over all test cases does not exceed 1800 . DeepL 翻译    输入 每个测试包含多个测试用例。第一行包含测试用例的数量 t ( 1≤t≤103 )。测试用例说明如下。 每个测试用例的第一行包含两个整数 n 和 k ( 1≤n≤105 、 k 、 k )。( 1≤n≤105 , 1≤k≤360 )、好友人数和最大纸牌总数。 每个测试用例的第二行包含 n 个整数 a1,a2,…,an ( 0≤ai≤k ),即每个好友可携带的最大纸牌数。 保证所有测试用例的 n 之和不超过 5⋅105 ,所有测试用例的 k 之和不超过 1800 。    Output For each test case, output the maximum happiness Little A can get. DeepL 翻译    输出 针对每个测试案例,输出小 A 能获得的最大幸福感。 Example InputCopy 4 3 4 0 0 1 6 8 1 2 0 5 1 8 3 4 1 0 4 5 8 2 4 5 4 3 OutputCopy 1 20 5 19    Note In the first test case, the only way to distribute wishing cards is b=[0,0,1] . In the third test case, b=[1,0,4] is invalid because you only have k=4 wishing cards. In the fourth test case, one of the optimal ways to distribute wishing cards is to set b=[2,0,5,0,0] , in which Little A will gain 2+2+5+5+5=19 happiness. DeepL 翻译    注 在第一个测试案例中,分发许愿卡的唯一方法是 b=[0,0,1] 。 在第三个测试案例中, b=[1,0,4] 是无效的,因为你只有 k=4 张许愿卡。
12-11
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值