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

Problem Description

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:

Solutions

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;
    }
}

Loading editor...