Advertisement
Ligh7_of_H3av3n

6.Equal Sums

Jan 26th, 2024
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. package Uprajneniq;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class EqualSums {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         // Read space-separated integers from the user
  10.         String[] input = scanner.nextLine().split(" ");
  11.         int[] arr = new int[input.length];
  12.         for (int i = 0; i < input.length; i++) {
  13.             arr[i] = Integer.parseInt(input[i]);
  14.         }
  15.  
  16.         // Find and print the index where sums are equal
  17.         System.out.println(findEqualSumIndex(arr));
  18.  
  19.         scanner.close();
  20.     }
  21.  
  22.     public static String findEqualSumIndex(int[] arr) {
  23.         for (int i = 0; i < arr.length; i++) {
  24.             int leftSum = 0;
  25.             int rightSum = 0;
  26.  
  27.             // Calculate sum of elements on the left side
  28.             for (int j = 0; j < i; j++) {
  29.                 leftSum += arr[j];
  30.             }
  31.  
  32.             // Calculate sum of elements on the right side
  33.             for (int k = i + 1; k < arr.length; k++) {
  34.                 rightSum += arr[k];
  35.             }
  36.  
  37.             // Check if sums are equal
  38.             if (leftSum == rightSum) {
  39.                 return Integer.toString(i);
  40.             }
  41.         }
  42.  
  43.         return "no";
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement