This is a Leetcode problem -
Given an array which consists of non-negative integers and an integer
m
, you can split the array intom
non-empty continuous subarrays. Write an algorithm to minimize the largest sum among thesem
subarrays.Note -
If
n
is the length of the array, assume the following constraints are satisfied:
- 1 ≤
n
≤ 1000- 1 ≤
m
≤ min(50,n
)
Here is my solution to this challenge -
class Solution(object): def __init__(self, nums, m): self.nums = nums self.m = m def split_array(self, nums, m): """ :type nums: List[int] :type m: int :rtype: int """ min_res = max(nums) max_res = sum(nums) low, high = min_res, max_res while low + 1 < high: mid = low + (high - low)//2 if self.is_valid(nums, m, mid): high = mid else: low = mid if self.is_valid(nums, m, low): return low return high def is_valid(self, nums, m, n): count, current = 1, 0 for i in range(len(nums)): if nums[i] > n: return False current += nums[i] if current > n: current = nums[i] count += 1 if count > m: return False return True
Here, I just optimize the binary search method (technique used to search an element in a sorted list), change the condition of low <= high
to low + 1 < high
and mid = low + (high - low) / 2
in case low + high
is larger than the max int
.
Here is an example input/output -
output = Solution([7,2,5,10,8], 2)
print(output.split_array([7,2,5,10,8], 2))
>>> 18
Explanation -
There are four ways to split nums
into two subarrays.
The best way is to split it into [7,2,5]
and[10,8]
,
where the largest sum among the two subarrays is only 18
.
Here is the time for this output -
%timeit output.split_array([7,2,5,10,8], 2)
12.7 µs ± 512 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
So, I would like to know whether I could make this program shorter and more efficient.