📌  相关文章
📜  给定数组中可被 M 整除的最大 K 位整数

📅  最后修改于: 2022-05-13 01:56:08.601000             🧑  作者: Mango

给定数组中可被 M 整除的最大 K 位整数

给定一个大小为N的数组arr[]和 2 个整数KM ,任务是从数组arr[]中找到可被M整除的K位的最大整数。如果不可能找到任何这样的整数,则打印-1

例子:

朴素方法:这可以通过查找所有大小为 K 的子序列然后检查条件以找到最大的子序列来完成。
时间复杂度: O(2 N )
辅助空间:O(1)

有效方法:这个想法是检查数组中M的倍数中的每个数字是否有可能形成该数字。如果可能,请更新答案。请按照以下步骤解决问题:

  • 如果K大于N,则打印-1并返回。
  • 用值0初始化大小为10的向量freq[]以存储数组arr[] 的所有元素的频率。
  • 遍历范围[0, N)并将每个元素的频率存储在数组freq[] 中。
  • 按升序对数组arr[]进行排序。
  • 初始化变量X并将其值设置为数组arr[]中最大的K位数作为可能的最大数。
  • 如果X小于M则打印-1并返回。
  • 将变量answer初始化为-1以存储答案。
  • 使用变量i迭代范围[M, X]并执行以下步骤:
    • 将变量y初始化为i。
    • 用值0初始化大小为10的向量v[]以存储数字y 的所有数字的频率。
    • 遍历向量freq[]v[] ,如果对于所有位置freq[j]大于等于v[j],则将答案更新为 answery 的最大值。
  • 执行上述步骤后,打印变量answer作为答案。

下面是上述方法的实现。

C++14
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the largest integer
// of K digits divisible by M
void find(vector& arr, int N, int K, int M)
{
 
    // Base Case, as there is no sub-sequence
    // of size greater than N is possible
    if (K > N) {
        cout << "-1\n";
        return;
    }
 
    // Vector to store the frequency of each
    // number from the array
    vector freq(10, 0);
 
    // Calculate the frequency of each from
    // the array
    for (int i = 0; i < N; i++) {
        freq[arr[i]]++;
    }
 
    // Sort the array in ascending order
    sort(arr.begin(), arr.end());
 
    // Variable to store the maximum number
    // possible
    int X = 0;
 
    // Traverse and store the largest K digits
    for (int i = N - 1; K > 0; i--) {
        X = X * 10 + arr[i];
        K--;
    }
 
    // Base Case
    if (X < M) {
        cout << "-1\n";
        return;
    }
 
    // Variable to store the answer
    int answer = -1;
 
    // Traverse and check for each number
    for (int i = M; i <= X; i = i + M) {
        int y = i;
        vector v(10, 0);
 
        // Calculate the frequency of each number
        while (y > 0) {
            v[y % 10]++;
            y = y / 10;
        }
 
        bool flag = true;
 
        // If frequency of any digit in y is less than
        // that in freq[], then it's not possible.
        for (int j = 0; j <= 9; j++) {
            if (v[j] > freq[j]) {
                flag = false;
                break;
            }
        }
 
        if (flag)
            answer = max(answer, i);
    }
 
    // Print the answer
    cout << answer << endl;
}
 
// Driver Code
int main()
{
 
    vector arr = { 1, 2, 3, 4, 5, 6 };
    int N = 6, K = 3, M = 4;
 
    find(arr, N, K, M);
 
    return 0;
}


Java
// Java code for the above approach
import java.io.*;
import java.util.Arrays;;
class GFG
{
   
    // Function to find the largest integer
    // of K digits divisible by M
    static void find(int[] arr, int N, int K, int M)
    {
 
        // Base Case, as there is no sub-sequence
        // of size greater than N is possible
        if (K > N) {
            System.out.println("-1\n");
            return;
        }
 
        // Vector to store the frequency of each
        // number from the array
        int freq[] = new int[10];
 
        // Calculate the frequency of each from
        // the array
        for (int i = 0; i < N; i++) {
            freq[arr[i]]++;
        }
 
        // Sort the array in ascending order
        Arrays.sort(arr);
 
        // Variable to store the maximum number
        // possible
        int X = 0;
 
        // Traverse and store the largest K digits
        for (int i = N - 1; K > 0; i--) {
            X = X * 10 + arr[i];
            K--;
        }
 
        // Base Case
        if (X < M) {
            System.out.println("-1");
            return;
        }
 
        // Variable to store the answer
        int answer = -1;
 
        // Traverse and check for each number
        for (int i = M; i <= X; i = i + M) {
            int y = i;
            int v[] = new int[10];
 
            // Calculate the frequency of each number
            while (y > 0) {
                v[y % 10]++;
                y = y / 10;
            }
 
            boolean flag = true;
 
            // If frequency of any digit in y is less than
            // that in freq[], then it's not possible.
            for (int j = 0; j <= 9; j++) {
                if (v[j] > freq[j]) {
                    flag = false;
                    break;
                }
            }
 
            if (flag)
                answer = Math.max(answer, i);
        }
 
        // Print the answer
        System.out.println(answer);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int N = 6, K = 3, M = 4;
 
        find(arr, N, K, M);
    }
}
 
// This code is contributed by Potta Lokesh


Python3
# Python program for the above approach
 
# Function to find the largest integer
# of K digits divisible by M
def find(arr, N, K, M):
 
    # Base Case, as there is no sub-sequence
    # of size greater than N is possible
    if (K > N):
        print("-1")
        return
 
    # Vector to store the frequency of each
    # number from the array
    freq = [0] * 10
 
    # Calculate the frequency of each from
    # the array
    for i in range(N):
        freq[arr[i]] += 1
 
    # Sort the array in ascending order
    arr.sort()
 
    # Variable to store the maximum number
    # possible
    X = 0
 
    # Traverse and store the largest K digits
    for i in range(N - 1, 2, -1):
        X = X * 10 + arr[i]
        K -= 1
 
    # Base Case
    if (X < M):
        print("-1")
        return
 
    # Variable to store the answer
    answer = -1
 
    # Traverse and check for each number
    for i in range(M, X + 1, M):
        y = i
        v = [0] * 10
 
        # Calculate the frequency of each number
        while (y > 0):
            v[y % 10] += 1
            y = y // 10
 
        flag = True
 
        # If frequency of any digit in y is less than
        # that in freq[], then it's not possible.
        for j in range(10):
            if (v[j] > freq[j]):
                flag = False
                break
 
        if (flag):
            answer = max(answer, i)
 
    # Print the answer
    print(answer)
 
 
# Driver Code
arr = [1, 2, 3, 4, 5, 6]
N = 6
K = 3
M = 4
 
find(arr, N, K, M)
 
# This code is contributed by gfgking.


C#
// C# code for the above approach
using System;
 
public class GFG
{
 
    // Function to find the largest integer
    // of K digits divisible by M
    static void find(int[] arr, int N, int K, int M)
    {
 
        // Base Case, as there is no sub-sequence
        // of size greater than N is possible
        if (K > N) {
            Console.WriteLine("-1\n");
            return;
        }
 
        // Vector to store the frequency of each
        // number from the array
        int []freq = new int[10];
 
        // Calculate the frequency of each from
        // the array
        for (int i = 0; i < N; i++) {
            freq[arr[i]]++;
        }
 
        // Sort the array in ascending order
        Array.Sort(arr);
 
        // Variable to store the maximum number
        // possible
        int X = 0;
 
        // Traverse and store the largest K digits
        for (int i = N - 1; K > 0; i--) {
            X = X * 10 + arr[i];
            K--;
        }
 
        // Base Case
        if (X < M) {
            Console.WriteLine("-1");
            return;
        }
 
        // Variable to store the answer
        int answer = -1;
 
        // Traverse and check for each number
        for (int i = M; i <= X; i = i + M) {
            int y = i;
            int []v = new int[10];
 
            // Calculate the frequency of each number
            while (y > 0) {
                v[y % 10]++;
                y = y / 10;
            }
 
            bool flag = true;
 
            // If frequency of any digit in y is less than
            // that in freq[], then it's not possible.
            for (int j = 0; j <= 9; j++) {
                if (v[j] > freq[j]) {
                    flag = false;
                    break;
                }
            }
 
            if (flag)
                answer = Math.Max(answer, i);
        }
 
        // Print the answer
        Console.WriteLine(answer);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int N = 6, K = 3, M = 4;
 
        find(arr, N, K, M);
    }
}
 
// This code is contributed by AnkThon


Javascript


输出
652

时间复杂度:O(max(M, N))
辅助空间:O(1)