RE60K
RE60K

Reputation: 621

Finding the two largest element of an array

For Problem:

Finding and printing unique team of two students (otherwise printing "?") from each region out of n regions based on greater scores (from 0 to 800)

I thought that we can keep track of the largest and second largest element, initialized with scores of -1 and -1. There are only a few possibilities:

But it seems this is wrong, but I don't know why?

Code:

import java.util.Arrays;
import java.util.Scanner;

public class B659 {
    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
    int n = num();
    int m = num();
    String[] rgn1 = new String[m]; // students with highest score in their region
    String[] rgn2 = new String[m]; // students with second-highest score in their region
    int[] rgn1s = new int[m]; // highest score in the regions
    int[] rgn2s = new int[m]; // second-highest score in the regions
    Arrays.fill(rgn1s, -1);
    Arrays.fill(rgn2s, -1);
    boolean[] und = new boolean[m];
    for (int i = 0; i < n; i++) {
        String sn = str();
        int r = num() - 1;
        int sc = num();
        if (sc > rgn1s[r]) {
        if (rgn2s[r] == rgn1s[r] && rgn1s[r] != -1) {
            und[r] = true;
            continue;
        } else {
            rgn2s[r] = rgn1s[r];
            rgn2[r] = rgn1[r];
        }
        rgn1s[r] = sc;
        rgn1[r] = sn;
        } else if (sc > rgn2s[r]) {
        rgn2s[r] = sc;
        rgn2[r] = sn;
        } else if (sc == rgn2s[r]) {
        und[r] = true;
        }
    }
    for (int i = 0; i < m; i++) {
        print((!und[i]) ? (rgn1[i] + " " + rgn2[i]) : "?");
    }
    }

    private static int num() {
    return sc.nextInt();
    }

    private static String str() {
    return sc.next();
    }

    private static void print(Object x) {
    System.out.println(x);
    }
}

Upvotes: 0

Views: 49

Answers (1)

Priyam Gupta
Priyam Gupta

Reputation: 250

Your code doesn't handle the situation when once the duplicate values has been encountered and the und[r] field has been set true, two higher values are encountered.

For eg:
6 2
Ram 1 200
Shyam 1 200
Raju 2 200
Rita 1 300
Hera 2 500
Sita 1 500

You need to redefine the if and add another else if part for the duplicate entries if they happens to be the last pair.

else if (sc == rgn1s[r]) {
        und[r] = true;
        }

For eg:
6 2
Ram 1 200
Shyam 1 300
Raju 2 200
Rita 1 500
Hera 2 500
Sita 1 500

Upvotes: 1

Related Questions