LeetCode 3441: Minimum Cost Good Caption Solution

Master LeetCode problem 3441 (Minimum Cost Good Caption), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3441. Minimum Cost Good Caption

Problem Explanation

Explanation

To solve this problem, we can iterate over the given caption and identify groups of consecutive characters. For each group, we need to determine the minimum number of operations required to make it a good caption. We can do this by checking if the group has 3 or more consecutive characters. If not, we can calculate the number of operations needed to make it a good caption by considering the characters before and after each character in the group.

After processing all groups, we need to find the lexicographically smallest good caption that requires the minimum total number of operations. We can achieve this by using dynamic programming and maintaining the minimum number of operations needed to reach each character at each index.

Solution Code

class Solution {
    public String minGoodCaption(String caption) {
        int n = caption.length();
        char[] chars = caption.toCharArray();
        int[] dp = new int[n];
        
        for (int i = 0; i < n; i++) {
            int count = 1;
            while (i + 1 < n && chars[i] == chars[i + 1]) {
                i++;
                count++;
            }
            
            for (int j = i; j >= i - count + 1; j--) {
                int left = j - 1 >= 0 ? chars[j - 1] : 'a';
                int right = j + 1 < n ? chars[j + 1] : 'z';
                dp[j] = Math.min(dp[j] + Math.min(chars[j] - left, right - chars[j]), dp[j] + 3 - count);
            }
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append((char) (chars[i] - dp[i]));
        }
        
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3441 (Minimum Cost Good Caption)?

This page provides optimized solutions for LeetCode problem 3441 (Minimum Cost Good Caption) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3441 (Minimum Cost Good Caption)?

The time complexity for LeetCode 3441 (Minimum Cost Good Caption) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3441 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3441 in Java, C++, or Python.

Back to LeetCode Solutions