Ajay Kumar Sinha
Ajay Kumar Sinha

Reputation: 41

Matching pairs of array

I have an array with integers, I just have to count the pairs and return that counted value.

static int StockMerchant(int n , int arr[]){
    int[] temp = new int[n];
    int count = 0;
    for(int i =0  ; i<n ; i++){
            for(int j= i+1 ; j<n ; j++){

                if(arr[i]==arr[j]){

                   arr[j] = '0';
                   arr[i] ='0';
                   count++;
                }
            }


    }
        return count;
}

when I try: 1 1 2 2 2: gives output 2

But when I change the input to 1 2 1 2 2: gives output 3

I want the output to be 2 in the second case also. please help.

Upvotes: 1

Views: 1721

Answers (2)

Sourish Mukherjee
Sourish Mukherjee

Reputation: 179

*Sorry for my bad paint skills.

Hope I was able to point out your mistake:)

Mistake

Here is my solution : Its basically sorting the array first and checking if it matches the value increment i position to j+1 and j as i+1

static int StockMerchant(int n, int arr[]) {
        Arrays.sort(arr);
        int count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (arr[i] == arr[j]) {
                    i = j + 1;
                    j = i;
                    count++;
                }
            }

        }
        return count;
    }

Upvotes: 1

Tanish
Tanish

Reputation: 59

Here i'm assuming all your test inputs contains positive integers, this logic works for the positive values only.

static int StockMerchant(int n , int arr[]){
            int starter = n>0 && arr[0] != 0 ? 0 : -1;
            int temp = starter;
            int count = 0;
            Arrays.sort(arr);
            for(int i =0  ; i<n ; i++){
                if(temp == arr[i]){
                    temp = starter;
                    count++;
                }else{
                    temp = arr[i];
                }
            }
            return count;
        }

Upvotes: 0

Related Questions