fork download
  1. import java.util.HashMap;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int[] A = {0, 1, 2, 3}; // Using 1-based indexing layout
  6. int[] B = {0, 2, 1, 3};
  7. int n = 3;
  8.  
  9. int[] prefixA = new int[n + 1];
  10. int[] prefixB = new int[n + 1];
  11.  
  12. // Step 1: Build prefix sums
  13. for (int i = 1; i <= n; i++) {
  14. prefixA[i] = prefixA[i - 1] + A[i];
  15. prefixB[i] = prefixB[i - 1] + B[i];
  16. }
  17. //Here, instead of looking for a constant K, we are looking for a subarray where Sum of A = Sum of B.
  18. //If you subtract the sum of B from the sum of A, you get:Sum of A - Sum of B = 0
  19. // Step 2: Use HashMap to track first occurrence of (prefixA[k] - prefixB[k])
  20. HashMap<Integer, Integer> firstOccurrence = new HashMap<>();
  21. int maxG = 0;
  22.  
  23. for (int j = 0; j <= n; j++) {
  24. int diff = prefixA[j] - prefixB[j];
  25.  
  26. if (firstOccurrence.containsKey(diff)) {
  27. int prevIndex = firstOccurrence.get(diff);
  28. int currentLength = j - prevIndex;
  29. maxG = Math.max(maxG, currentLength);
  30. } else {
  31. // Store the earliest index to maximize length
  32. firstOccurrence.put(diff, j);
  33. }
  34. }
  35.  
  36. System.out.println("Max length G: " + maxG);
  37. }
  38. }
Success #stdin #stdout 0.09s 55520KB
stdin
10
5 -2 3 -4 1 6 -3 2 4 -1
2 1 -1 3 5 2 4 -2 1 3
stdout
Max length G: 3