Maximum Valid Graphene Segment

Anonymous
java
02/12/2026 6:36 PM
1.9 KB
9
Indexable
class Solution {
    public int maxValidSegment(int[] bondEnergy, int min_len, int targetMean, 
                               int diff_max, int pro_factor) {
        
        int n = bondEnergy.length;
        int left = 0;
        long sum = 0;
        int maxSum = 0;
        
        for (int right = 0; right < n; right++) {
            
            // If adjacent difference exceeds limit, reset window
            if (right > 0 && 
                Math.abs(bondEnergy[right] - bondEnergy[right - 1]) > diff_max) {
                
                left = right;
                sum = 0;
            }
            
            sum += bondEnergy[right];
            
            // Shrink if needed
            while (left <= right) {
                
                int length = right - left + 1;
                
                if (length < min_len) break;
                
                // Check mean condition
                if (sum == (long)targetMean * length) {
                    
                    long product = (long)bondEnergy[left] * bondEnergy[right];
                    
                    if (product % pro_factor == 0) {
                        maxSum = Math.max(maxSum, (int)sum);
                    }
                }
                
                // Try shrinking window
                sum -= bondEnergy[left];
                left++;
            }
        }
        
        return maxSum;
    }
}
Editor is loading...
Leave a Comment