672. Maximum Font To Fit A Sentence In A Screen

You are given a screen with a width W and a height H. You want to display a given sentence text using a font of size fontSize. The available font sizes are given in an array fonts.

A font of size fontSize has the following properties:

  • Each character in text has a width of fontSize * w.
  • Each line can hold floor(W / (fontSize * w)) characters.
  • The height of each line is fontSize * h.

Determine the maximum font size from fonts that allows text to fit within the screen (W × H). If no font size fits, return -1.

Example 1:

Input: text = "helloworld", w = 80, h = 20, fonts = [6,8,10,12,14,16,18,24,36]

Output: 6

Explanation:

Font Size = 6:

Character width = 6 * 1 = 6

Characters per line = 80 / 6 ≈ 13 → Fits

Character height = 6 * 1 = 6

Total height needed = 1 * 6 = 6 (since the text fits in one line) → Fits

Font Size = 8 and larger:

Will exceed height limit.

The largest font size that fits is 6.

Example 2:

Input: text = "leetcode", w = 1000, h = 50, fonts = [1,2,4]

Output: 4

Explanation:

Font Size = 1:

Character width = 1 * 1 = 1

Characters per line = 1000 / 1 = 1000 → Fits

Character height = 1 * 1 = 1

Total height needed = 1 * 1 = 1 → Fits

Font Size = 2:

Character width = 2 * 1 = 2

Characters per line = 1000 / 2 = 500 → Fits

Character height = 2 * 1 = 2

Total height needed = 1 * 2 = 2 → Fits

Font Size = 4:

Character width = 4 * 1 = 4

Characters per line = 1000 / 4 = 250 → Fits

Character height = 4 * 1 = 4

Total height needed = 1 * 4 = 4 → Fits

The largest font that fits is 4.

Now Your Turn!

Pick the correct output for the given input

Input: text = "easyquestion", w = 100, h = 100, fonts = [10,15,20,25]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= text.length <= 50000
  • text contains only lowercase English letters.
  • 1 <= w <= 107
  • 1 <= h <= 104
  • 1 <= fonts.length <= 105
  • 1 <= fonts[i] <= 105
  • fonts is sorted in ascending order and does not contain duplicates.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* // This is the FontInfo's API interface.
* // You should not implement it, or speculate about its implementation
* class FontInfo {
* public:
* // Return the width of char ch when fontSize is used.
* int getWidth(int fontSize, char ch);
*
* // Return Height of any char when fontSize is used.
* int getHeight(int fontSize)
* };
*/
class Solution {
public:
int maxFont(string text, int w, int h, vector<int>& fonts, FontInfo fontInfo) {
// Your Code Goes Here
}
};
Test Case

Input:

Fonts
H
Text
W