Problem 1760

Abstract / Summary

Given balls of k types and a limit for each bag, find the minimum limit so all balls can be placed in bags without exceeding the limit in any bag.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1760.py

class Solution:
    def minimumSize(self, nums: List[int], maxOperations: int) -> int:
        # steps required to split each bag such that it fits the maximum size
        def steps(size):
            result = 0
            for n in nums:
                if n > size:
                    # break down each oversized bag into bags of size "size"
                    smaller = ceil(n / size)
                    result += smaller - 1
            return result

        left  = 1
        right = max(nums)
        while left != right:
            mid = (left + right) // 2
            if steps(mid) > maxOperations:
                left  = mid + 1
            else:
                right = mid

        return left
22 lines | 735 bytes | submitted November 24, 2023 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of determining the smallest possible maximum bag size after performing at most a given number of split operations on an array of bag volumes. It does this by repeatedly checking whether a candidate size can be achieved within the allowed number of operations and narrowing the search space until the optimal size is found.

Key Steps

Helper that counts required operations

def steps(size):
    result = 0
    for n in nums:
        if n > size:
            smaller = ceil(n / size)
            result += smaller - 1
    return result

The inner function iterates over every element in the input list. For each bag larger than the candidate size, it computes how many sub-bags are needed (ceil(n / size)) and adds the number of splits required (smaller - 1) to a running total. The final total represents the minimum number of operations needed to ensure no bag exceeds size.

Setting the binary-search bounds

left  = 1
right = max(nums)

The search interval is initialized with the smallest feasible size (1) and the largest existing bag size (max(nums)). This guarantees that the answer lies somewhere within the interval.

Binary-search loop that converges on the answer

while left != right:
    mid = (left + right) // 2
    if steps(mid) > maxOperations:
        left  = mid + 1
    else:
        right = mid

During each iteration the midpoint of the current interval is examined. The helper steps determines how many operations would be required to achieve that midpoint as the maximum bag size. If the required operations exceed the allowed limit, the lower bound is moved just above mid; otherwise the upper bound is moved down to mid. The loop terminates when the lower and upper bounds meet, indicating that the smallest feasible size has been isolated.

Returning the minimal feasible size

return left

At termination left (which equals right) holds the minimal maximum bag size that can be achieved with at most maxOperations splits, and this value is returned as the final result.

Edge Cases Handled

When every bag already fits within the candidate size, the helper function adds nothing to the operation count, allowing the binary search to quickly converge to the current maximum bag size. If maxOperations is zero, the algorithm effectively searches for the smallest size that requires no splits, which will be the original maximum element. The lower bound of 1 ensures that even the extreme case where all bags consist of a single unit is considered, preventing an infinite loop. The use of ceil guarantees correct rounding up for division, handling cases where a bag size is not an exact multiple of the candidate size.

Performance Optimizations

The algorithm leverages binary search to reduce the number of candidate sizes examined from linear in the range of bag values to logarithmic, dramatically cutting the number of calls to the steps helper. Inside steps, the computation ceil(n / size) is performed using integer arithmetic, avoiding floating-point overhead. By accumulating the required operations in a single pass over nums and exiting the loop only after all elements are processed, the implementation minimizes redundant work. The early decision in the binary-search loop-moving the bounds based on a single comparison-prevents unnecessary further evaluation of sizes that are already known to be infeasible.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there are several bags filled with marbles. Some bags are huge and some are tiny. A game needs these bags to be small enough so that no bag has more marbles than a certain limit. There is only a small number of times allowed to split a big bag into two smaller ones.

To solve this, the code acts like it is testing out different size limits to see which one works best. It starts by picking a middle size between the smallest possible bag and the biggest bag. Then, it looks at every bag of marbles. If a bag is bigger than the middle size, it figures out how many times that bag needs to be split to make all the pieces fit the limit. It adds up all those splits to see if they fit within the allowed number of operations.

If the total number of splits is too high, it means the size limit was too small, so it tries a larger size. If the total number of splits works out, it remembers that size and tries to see if an even smaller size could also work. By doing this over and over, it slowly zooms in until it finds the smallest possible size that still fits within the rules.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.85 | σ = 1.21

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ JS Python Java C# Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
Shamik07 Dart
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
Shamik07 Dart
suxrobGM C#
27 links | 13 authors | 9 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   November 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality