1
- # Problem Statement: https://leetcode.com/problems/split-array-largest-sum/
1
+ # Problem Statement: https://leetcode.com/problems/split-array-largest-sum/
2
+
3
+ class Solution :
4
+ def splitArray (self , nums : List [int ], m : int ) -> int :
5
+ # First, understand WHAT we are binary searching over
6
+ # we are doing a binary search over the *search space of possible results*
7
+ # What is the search space, aka what are all possible results?
8
+ # For this, we need to know the minimum and maximum possible result
9
+ ## minimum possible result - largest element in array. Since each element needs
10
+ # to be part of some subarray, the smallest we can go is by taking the largest element
11
+ # in a subarray by itself
12
+ ## maximum possible result - sum of all elements in the array since we cannot form
13
+ # a subarray larger than the array itself
14
+ # Compute minResult and maxResult boundaries
15
+ minResult , maxResult = 0 ,0
16
+ for num in nums :
17
+ maxResult += num
18
+ if num > minResult :
19
+ minResult = num
20
+
21
+ # now that we have our minResult and maxResult boundaries, we can begin searching within this space
22
+ # What are we searching for?
23
+ # The smallest value within this space such that we can form m subarrays from nums and none of their sums exceed that value
24
+ finalResult = float ('inf' )
25
+ while minResult <= maxResult :
26
+ # Start by checking if the value in the middle of the search space satisfies this desired outcome
27
+ # If it does, we can discard all values to the right of this in our search space since we have
28
+ # something better than those already. We only need to search values to the left to see if
29
+ # we can find something better
30
+ # If not, we only need to search values higher than mid
31
+ mid = (minResult + maxResult ) // 2
32
+ if self .isPossibility (mid , nums , m ):
33
+ finalResult = mid
34
+ maxResult = mid - 1
35
+ else :
36
+ minResult = mid + 1
37
+ return finalResult
38
+
39
+ # Checks to see if x is a valid possibility given the constraint of m subarrays
40
+ def isPossibility (self , x , nums , m ):
41
+ numSubarrays = 1
42
+ subarraySum = 0
43
+ for num in nums :
44
+ # Greedily try to add this element to the current subarray as long as the subarray's sum doesn't exceed our upper limit x
45
+ if (num + subarraySum ) <= x :
46
+ subarraySum += num
47
+ # If sum would be exceeded by adding the current element, we need to start a new subarray and put this element into that
48
+ else :
49
+ numSubarrays += 1
50
+ subarraySum = num
51
+
52
+ return (numSubarrays <= m )
0 commit comments