LeetCode 1618: Maximum Font to Fit a Sentence in a Screen Solution

Master LeetCode problem 1618 (Maximum Font to Fit a Sentence in a Screen), a medium 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.

1618. Maximum Font to Fit a Sentence in a Screen

Problem Explanation

Explanation:

Given a sentence and some parameters related to screen size and font sizes, we need to find the maximum font size that can be used to display the entire sentence on the screen.

To solve this problem, we can use binary search to find the maximum font size that fits the given sentence within the screen constraints. We can iteratively check if a particular font size can fit the sentence on the screen by calculating the width of the sentence with that font size. If the width exceeds the screen width, we decrease the font size; otherwise, we try increasing the font size. Solution:

Solution Code

class Solution {
    public int maxFont(String text, int w, int h, int[] letters, int font, int perLetter) {
        int low = 1, high = font;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (canFit(text, w, h, letters, mid, perLetter)) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return high;
    }
    
    private boolean canFit(String text, int w, int h, int[] letters, int font, int perLetter) {
        int width = 0;
        int maxHeight = 0;
        for (char c : text.toCharArray()) {
            int size = letters[c - 'a'];
            width += size * font / perLetter;
            maxHeight = Math.max(maxHeight, size);
        }
        return width <= w && maxHeight <= h;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1618 (Maximum Font to Fit a Sentence in a Screen)?

This page provides optimized solutions for LeetCode problem 1618 (Maximum Font to Fit a Sentence in a Screen) 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 1618 (Maximum Font to Fit a Sentence in a Screen)?

The time complexity for LeetCode 1618 (Maximum Font to Fit a Sentence in a Screen) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1618 on DevExCode?

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

Back to LeetCode Solutions