Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum Arithmetic sequence of two different array

Given two arrays of ints, a and b, try to create an arithmetic sequence by adding ints from b into a. Return the maximum length of a or -1 if there does not exist an arithmetic sequence e.g. a = [2, 4, 8], b = [1, 6, 10, 12] -> a = [2, 4, 6, 8, 10, 12] -> return 6

I tried creating a new array and merging both a and b and counting the longest subsequence but the count could remove elements from a which should not be touched

static int maxSeq(int[] arr1, int[] arr2){
        if(arr1.length ==0)return 0;
        int n =arr1.length, m = arr2.length;
        int[] arr = new int[n+m];
        System.arraycopy(arr1,0,arr,0,n);
        System.arraycopy(arr2,0,arr,n,m);
        Arrays.sort(arr);
        int result =0;
        Map<Integer,Integer>[]d = new HashMap[n+m];
        for(int i =0; i < arr.length;i++){
            d[i] = new HashMap<Integer, Integer>();
        }
        for(int i =1; i < arr.length; ++i){
            for(int j = 0; j<i;++j ){
                int diff = arr[i]-arr[j];

                int len =2;

                if(d[j].containsKey(diff)){
                    len = d[j].get(diff) +1;
                }



                d[i].put(diff,len);

                result = Math.max(result,d[i].get(diff));


            }
        }
        return result;
    }

a = [2, 4, 8], b = [1, 6, 10, 12] -> a = [2, 4, 6, 8, 10, 12] -> return 6 int[] a = {5,7,13,14}, b = {9,11,15}; return -1 not 6

like image 600
kusiroll Avatar asked Mar 05 '26 19:03

kusiroll


1 Answers

I think you should try to fix your code.

if(d[j].containsKey(diff)){ len = d[j].get(diff) +1; }

Here you are looking for differences in a map of some index j, and there should be only one map of key value paires, not array of maps.