882031. Longest Subarray with Majority Greater than K
Medium
Longest Subarray with Majority Greater than K
Slug: longest-subarray-with-majority-greater-than-k
Difficulty: Medium
Id: 882031
Topic Tags: prefix-sum, Hash
Company Tags: None
Summary
Given an array of integers and a number K, find the length of the longest subarray where the majority element is greater than K. The majority element is the element that appears more than half the size of the subarray.
Detailed Explanation
To solve this problem, we can use the prefix sum technique to keep track of the cumulative count of elements greater than K in each subarray. We maintain a hashmap to store the prefix sums and their corresponding indices.
Here's a step-by-step breakdown of the solution:
- Initialize a hashmap
cumulative_sumto store the prefix sums and their indices. - Iterate through the array, maintaining a running sum
cumulative_sum. - For each element in the array, calculate the cumulative sum by adding the current element to the previous cumulative sum.
- Check if the cumulative sum is greater than or equal to
K. If it is, increment the count of majority elements. - Update the hashmap with the current cumulative sum and its index.
- Initialize a variable
max_lengthto store the length of the longest subarray. - Iterate through the hashmap, updating
max_lengthwhenever we find a prefix sum that has more than half the size of the array. - Return
max_length.
Time complexity: O(n), where n is the size of the input array. Space complexity: O(n), for storing the cumulative sums and their indices in the hashmap.
Optimized Solutions
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static int longestSubarray(int[] arr, int K) {
Map<Integer, Integer> cumulativeSum = new HashMap<>();
int cumulativeSumCount = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > K) {
cumulativeSumCount++;
} else {
cumulativeSumCount -= 1;
}
cumulativeSum.put(cumulativeSumCount, i);
}
int maxLength = 0;
for (int sum : cumulativeSum.keySet()) {
if ((sum >= 0 && cumulativeSumCount - sum > K) || sum < 0) {
maxLength = Math.max(maxLength, cumulativeSum.get(sum + K));
}
}
return maxLength;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int K = 3;
System.out.println(longestSubarray(arr, K)); // Output: 3
}
}