Education + Jobs Hiring Website - 2025
0 like 0 dislike
541 views

in Online Assessments by Expert (139,590 points) 1 flag | 541 views
0 0
public static long getMinCost(int[] arr) {
    int n = arr.length;
    if (n == 1) return 0;
    
    long minCost = Long.MAX_VALUE;
    int currentLength = 1;
    
    for (int i = 1; i < n; i++) {
        if (arr[i] == arr[i-1]) {
            currentLength++;
        } else {
            // Calculate cost for the previous group
            long cost = (long)(n - currentLength) * arr[i-1];
            minCost = Math.min(minCost, cost);
            currentLength = 1;
        }
    }
    
    // Don't forget the last group
    long cost = (long)(n - currentLength) * arr[n-1];
    minCost = Math.min(minCost, cost);
    
    return minCost;
}

1 Answer

0 like 0 dislike
public static long getMinCost(int[] arr) {
    int n = arr.length;
    if (n == 1) return 0;
    
    long minCost = Long.MAX_VALUE;
    int currentLength = 1;
    
    for (int i = 1; i < n; i++) {
        if (arr[i] == arr[i-1]) {
            currentLength++;
        } else {
            // Calculate cost for the previous group
            long cost = (long)(n - currentLength) * arr[i-1];
            minCost = Math.min(minCost, cost);
            currentLength = 1;
        }
    }
    
    // Don't forget the last group
    long cost = (long)(n - currentLength) * arr[n-1];
    minCost = Math.min(minCost, cost);
    
    return minCost;
}
ago by (220 points)