diff --git a/problems/0410-split-array-largest-sum/solution.py b/problems/0410-split-array-largest-sum/solution.py new file mode 100644 index 0000000..798a53b --- /dev/null +++ b/problems/0410-split-array-largest-sum/solution.py @@ -0,0 +1,22 @@ +def pieces_needed(nums: list[int], limit: int) -> int: + pieces = 1 + total = limit + for num in nums: + if total - num >= 0: + total -= num + else: + total = limit - num + pieces += 1 + return pieces + + +class Solution: + def splitArray(self, nums: list[int], k: int) -> int: + lo, hi = max(nums), sum(nums) + while lo < hi: + limit = (lo + hi) // 2 + if pieces_needed(nums, limit) > k: + lo = limit + 1 + else: + hi = limit + return lo diff --git a/problems/0410-split-array-largest-sum/solution_test.py b/problems/0410-split-array-largest-sum/solution_test.py new file mode 100644 index 0000000..085761f --- /dev/null +++ b/problems/0410-split-array-largest-sum/solution_test.py @@ -0,0 +1,13 @@ +import pytest +from solution import Solution + + +@pytest.mark.parametrize( + "nums, k, expected", + [ + ([7, 2, 5, 10, 8], 2, 18), + ([1, 2, 3, 4, 5], 2, 9), + ], +) +def test_split_array(nums, k, expected): + assert Solution().splitArray(nums, k) == expected