You are given an array nums of length n and an integer m. You need to determine if it is possible to split the array into n arrays of size 1 by performing a series of steps.
An array is called good if:
The length of the array is one , or
The sum of the elements of the array is greater than or equal to m.
In each step, you can select an existing array (which may be the result of previous steps) with a length of at least two and split it into two arrays, if both resulting arrays are good.
Return true if you can split the given array into n arrays, otherwise return false.
Input: nums =[2,2,1], m =4Output: trueExplanation:
* Split `[2, 2, 1]` to `[2, 2]` and `[1]`. The array `[1]` has a length of one, and the array `[2, 2]` has the sum of its elements equal to `4 >= m`, so both are good arrays.* Split `[2, 2]` to `[2]` and `[2]`. both arrays have the length of one, so both are good arrays.
Input: nums =[2,1,3], m =5Output: falseExplanation:
The first move has to be either of the following:* Split `[2, 1, 3]` to `[2, 1]` and `[3]`. The array `[2, 1]` has neither length of one nor sum of elements greater than or equal to `m`.* Split `[2, 1, 3]` to `[2]` and `[1, 3]`. The array `[1, 3]` has neither length of one nor sum of elements greater than or equal to `m`.So as both moves are invalid(they do not divide the array into two good
arrays), we are unable to split `nums` into `n` arrays of size 1.
If there exists any split of the array into two non-empty parts such that both parts are good (i.e., have sum ≥ m or length 1), then we can always recursively split further. So, we just need to check if there is any split point where both left and right subarrays are good.
classSolution {
public:bool canSplitArray(vector<int>& nums, int m) {
int n = nums.size();
if (n <=2) return true;
for (int i =1; i < n; ++i) {
if (nums[i-1] + nums[i] >= m) return true;
}
return false;
}
};
classSolution {
publicbooleancanSplitArray(int[] nums, int m) {
int n = nums.length;
if (n <= 2) returntrue;
for (int i = 1; i < n; ++i) {
if (nums[i-1]+ nums[i]>= m) returntrue;
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funcanSplitArray(nums: IntArray, m: Int): Boolean {
if (nums.size <=2) returntruefor (i in1 until nums.size) {
if (nums[i-1] + nums[i] >= m) returntrue }
returnfalse }
}
1
2
3
4
5
6
7
8
9
classSolution:
defcanSplitArray(self, nums: list[int], m: int) -> bool:
n = len(nums)
if n <=2:
returnTruefor i in range(1, n):
if nums[i-1] + nums[i] >= m:
returnTruereturnFalse
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfncan_split_array(nums: Vec<i32>, m: i32) -> bool {
let n = nums.len();
if n <=2 { returntrue; }
for i in1..n {
if nums[i-1] + nums[i] >= m {
returntrue;
}
}
false }
}