Untitled

 avatar
unknown
plain_text
16 days ago
1.0 kB
2
Indexable
class Solution {
    public int[] minOperations(String boxes) {
        int n = boxes.length();
        int[] answer = new int[n];
        int prefixSumIdx = 0, prefixCount = 0;
        int totalSum = 0, totalCount = 0;

        // Precompute totalSum and totalCount
        for (int i = 0; i < n; i++) {
            if (boxes.charAt(i) == '1') {
                totalSum += i;
                totalCount++;
            }
        }

        // Iterate through each box
        for (int i = 0; i < n; i++) {
            // Prefix operations
            int prefixMinOps = (prefixCount * i) - prefixSumIdx;
            prefixSumIdx += boxes.charAt(i) == '1' ? i : 0;
            prefixCount += boxes.charAt(i) == '1' ? 1 : 0;
            // Suffix operations
            int suffixMinOps = (totalSum - prefixSumIdx) - (i * (totalCount - prefixCount));

            // Combine prefix and suffix operations
            answer[i] = prefixMinOps + suffixMinOps;
        }

        return answer;
    }
}
Leave a Comment