Untitled
unknown
java
9 months ago
1.6 kB
7
Indexable
import java.util.*;
public class MaxBeautyAfterRepaint {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Input number of blocks (n) and maximum repaints allowed (m)
        int n = sc.nextInt();
        int m = sc.nextInt();
        // Input the block colors
        int[] blockColors = new int[n];
        for (int i = 0; i < n; i++) {
            blockColors[i] = sc.nextInt();
        }
        // Input the favorite color
        int favoriteColor = sc.nextInt();
        // Calculate the maximum beauty value after at most m repaints
        int maxBeauty = getMaxBeauty(blockColors, n, m, favoriteColor);
        // Output the maximum beauty value
        System.out.println(maxBeauty);
        sc.close();
    }
    private static int getMaxBeauty(int[] blockColors, int n, int m, int favoriteColor) {
        int left = 0, maxBeauty = 0, repaintCount = 0;
        // Sliding window approach
        for (int right = 0; right < n; right++) {
            // Count blocks that need repainting
            if (blockColors[right] != favoriteColor) {
                repaintCount++;
            }
            // Shrink window if repaints exceed allowed m
            while (repaintCount > m) {
                if (blockColors[left] != favoriteColor) {
                    repaintCount--;
                }
                left++;
            }
            // Calculate the maximum beauty value for the current window
            maxBeauty = Math.max(maxBeauty, right - left + 1);
        }
        return maxBeauty;
    }
}
Editor is loading...
Leave a Comment