LeetCode 1031 Maximum Sum of Two Non-Overlapping Subarrays

Problem Statement

Maintain a sliding window of two sub arrays with length L and M and slide through. For each slide check two cases:
L first, or M first. Use prefix sum to speed up calculation of sum of a given sub array.

use std::cmp;

impl Solution {
pub fn max_sum_two_no_overlap(a: Vec<i32>, l: i32, m: i32) -> i32 {
let A = a.iter().scan(0, |sum, i| {*sum += *i; Some(*sum)}).collect::<Vec<_>>();
let (L, M) = (l as usize, m as usize);
let (mut ans, mut lmax, mut rmax) = (A[L + M - 1], A[L - 1], A[M - 1]);
for i in L + M..A.len() as usize {
lmax = cmp::max(lmax, A[i - M] - A[i - M - L]);
rmax = cmp::max(rmax, A[i - L] - A[i - L - M]);
ans = cmp::max(ans, cmp::max(A[i] - A[i - L] + rmax, A[i] - A[i - M] + lmax));
}
return ans;
}
}