首页 > 解决方案 > 如何找到可以通过连接给定数组的所有元素而不使用字符串来构造的最大连接数?

问题描述

实际上,我只是为此添加答案只是为了分享另一种方法,仅此而已。

约束:

1 <= N <= 1000

0 <= ar[i] <= 1000

第一行 N 表示数组中的元素个数

第二行由数组元素组成

例子:

2

100, 9

输出:9100

示例 2:

3

12、13、8

输出:81312

标签: javabacktracking

解决方案


此代码不适用于大数字,并且在时间复杂度方面不是有效的解决方案

由于一些误解,我的帖子被删除了,请考虑这是我的问题,我的解决方案只是因为有人建议编辑答案被添加到问题中作为“到目前为止我的代码:”

import java.io.*;
import java.util.*;


public class Solution 

{

    static long ans=0;

    public static void main(String[] args)
    {
        int N,count=0;
        long n;


        Scanner scan=new Scanner(System.in);
        N=scan.nextInt();

        long[] ar=new long[N];
        long[] vis=new long[N];
        for(int i=0;i<N;i++)
        {
            ar[i]=scan.nextLong();
            vis[i]=0;
            n=ar[i];
            while(n!=0)
           {
                n/=10;
                count++;//It counts the number of digits of all elements in the given array
           }

       }      

       int index=0;
       long val=0,a=0;
       int x=0;

       recur(ar,vis,index,N,count,val,a);
       System.out.println(ans);
    }

    static void recur(long ar[],long vis[],int index,int N,int count,long val,long a)
    {
        if(index==N)
        {
            ans=Math.max(ans,val);
            return;
        }
        for(int i=0,j=0;i<N;i++,j++)
        {
            if(vis[i]==0)
            {
                vis[i]=1;
                a=counter(ar[i]);//counter returns no. of digits in the current element
                count-=a;//this returned value is subtracted from the count(which is the number of digits of all elements in the array)

                val+=ar[i]*(Math.pow(10,count));// now the corresponding digit's place is multiplied with the element to make up the number

                recur(ar,vis,index+1,N,count,val,a);
                vis[i]=0;
                val-=ar[i]*(Math.pow(10,count));
                count+=a;
            }
        }
    }
    static long counter(long val)
    {
        int count=0;
        while(val!=0)
        {
            val/=10;
            count++;
        }
        return count;
    }
}

推荐阅读