20240121 Finished

This commit is contained in:
jackfiled 2024-01-21 16:41:47 +08:00
parent 6dfb09b4ef
commit c6c91fc81a
2 changed files with 69 additions and 1 deletions

View File

@ -23,3 +23,4 @@ mod p2744_find_maximum_number_of_string_pairs;
mod p2171_removing_minimum_number_of_magic_beans;
mod p2809_minimum_time_to_make_array_sum_at_most_x;
mod p2788_split_strings_by_separator;
mod p410_split_array_largest_sum;

View File

@ -0,0 +1,67 @@
/**
* [410] Split Array Largest Sum
*/
pub struct Solution {}
// submission codes start here
impl Solution {
fn check(nums: &Vec<i32>, value: i64, m: i32) -> bool {
let mut sum = 0i64;
let mut count = 1;
for i in nums {
let i = *i as i64;
if i + sum > value {
sum = i;
count += 1;
} else {
sum += i;
}
}
count <= m
}
pub fn split_array(nums: Vec<i32>, k: i32) -> i32 {
let mut right = 0i64;
let mut left = i64::MIN;
for i in &nums {
let i = *i as i64;
if i > left {
left = i;
}
right += i;
}
while left < right {
let mid = (left + right) / 2;
if Solution::check(&nums, mid, k) {
right = mid;
} else {
left = mid + 1;
}
}
left as i32
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_410() {
assert_eq!(Solution::split_array(vec![7,2,5,10,8], 2), 18);
assert_eq!(Solution::split_array(vec![1,2,3,4,5], 2), 9);
assert_eq!(Solution::split_array(vec![1,4,4], 3), 4);
}
}