Untitled
unknown
java
a year ago
1.5 kB
7
Indexable
import java.util.*; public class Solution { public static int solve(int N, List<Integer> A) { // Convert List to array for easier handling int[] nums = A.stream().mapToInt(i -> i).toArray(); // Initialize variables HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int maxLength = -1; int count = 0; // Iterate through the array for (int i = 0; i < nums.length; i++) { // Adjust the count based on the value count += (nums[i] == 1) ? 1 : -1; // Check if this count has been seen before if (map.containsKey(count)) { // Update the maximum length if this subarray is longer maxLength = Math.max(maxLength, i - map.get(count)); } else { // Store the first occurrence of this count map.put(count, i); } } // If no subarray was found, return -1 return (maxLength == 0) ? -1 : maxLength; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int N = Integer.parseInt(scan.nextLine().trim()); List<Integer> A = new ArrayList<>(N); for (int j = 0; j < N; j++) { A.add(Integer.parseInt(scan.nextLine().trim())); } int result = solve(N, A); System.out.println(result); } }
Editor is loading...
Leave a Comment