impl Solution {
pub fn max_points(points: Vec<Vec<i32>>) -> i64 {
let m = points.len();
let n = points[0].len();
let mut last_row: Vec<(i64, i64)> = Vec::with_capacity(n);
let mut this_row: Vec<(i64, i64)> = Vec::with_capacity(n);
let mut points_it = points.into_iter();
for (i, v) in points_it.next().unwrap().into_iter().enumerate() {
let i = i as i64;
let v = v as i64;
if last_row.last().map(|last| v > last.1 + last.0 - i).unwrap_or(true) {
while last_row.last().map(|last| last.1 <= v + last.0 - i).unwrap_or(false) {
last_row.pop();
}
last_row.push((i, v));
}
}
for row in points_it {
let mut candidate_it = last_row.drain(..).peekable();
let mut candidate = candidate_it.next().unwrap();
for (i, v) in row.into_iter().enumerate() {
let i = i as i64;
let v = v as i64;
if let Some(new_candidate) = candidate_it.next_if(|new_candidate| candidate.1 + candidate.0 + new_candidate.0 <= new_candidate.1 + 2 * i) {
candidate = new_candidate;
}
let v = v + candidate.1 - candidate.0.abs_diff(i) as i64;
if this_row.last().map(|last| v > last.1 + last.0 - i).unwrap_or(true) {
while this_row.last().map(|last| last.1 <= v + last.0 - i).unwrap_or(false) {
this_row.pop();
}
this_row.push((i, v));
}
}
drop(candidate_it);
std::mem::swap(&mut this_row, &mut last_row);
}
last_row.into_iter().map(|(_, v)| v).max().unwrap()
}
}