Advertisement
sanyakasarova

Even Pairs

Sep 7th, 2021
863
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.16 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.  
  7.         int n = Integer.parseInt(scanner.nextLine());
  8.         // For this problem, since we will be comparing two pairs at one time, we will be using two sums:
  9.         int sum1 = 0;
  10.         int sum2 = 0;
  11.  
  12.  
  13.         // We'll also have a variable for the max difference since if they aren't all equal we will need it:
  14.         int maxDifference = 0;
  15.  
  16.         for (int i = 0; i < n; i++) {
  17.             // In a single for loop we are reading a pair with each iteration:
  18.             int num1 = Integer.parseInt(scanner.nextLine());
  19.             int num2 = Integer.parseInt(scanner.nextLine());
  20.  
  21.             // On each even iteration (0, 2, 4...) we will be changing the first sum:
  22.             if (i % 2 == 0){
  23.                 sum1 = num1 + num2;
  24.             }else{ // On each odd iteration we'll be changing the second one:
  25.                 sum2 = num1 + num2;
  26.             }
  27.  
  28.             // This variable will keep the current difference between the pairs:
  29.             int difference = 0;
  30.  
  31.             // We check whether the sums aren't equal. Notice the first condition (i != 0) - it's important to have it,
  32.             // since otherwise we will be comparing the first sum with 0, since the second sum won't be changed yet:
  33.             if (i != 0 && sum1 != sum2){
  34.                 // The difference is calculated with the help of the abs method since we don't know which sum is bigger:
  35.                 difference = Math.abs(sum1 - sum2);
  36.                 // Then if the current difference is bigger than the maximum difference, we change its value:
  37.                 if (difference != 0 && difference > maxDifference){
  38.                     maxDifference = difference;
  39.                 }
  40.             }
  41.         }
  42.  
  43.         // Print the results:
  44.         // If the maxDifference is still 0, as we initialized it, then all pairs were equal:
  45.         if (maxDifference == 0){
  46.             System.out.printf("Yes, value=%d", sum1);
  47.         }
  48.         else{
  49.             System.out.printf("No, maxdiff=%d", maxDifference);
  50.         }
  51.  
  52.     }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement