LeetCode 1027. Longest Arithmetic Sequence

Problem Statement


use std::collections::HashMap;

impl Solution {
pub fn longest_arith_seq_length(a: Vec<i32>) -> i32 {
let mut dp: HashMap<i32, HashMap<usize, i32>> = HashMap::new();
let mut ans = 2;
for i in 0..a.len() {
for j in i + 1..a.len() {
let d = a[j] - a[i];
dp.entry(d).or_insert(HashMap::new());
let val = dp.get_mut(&d).unwrap();
let insert_val ;
if val.contains_key(&i) {
insert_val = val.get(&i).unwrap().clone() + 1;
} else {
insert_val = 2;
}
val.insert(j, insert_val);
ans = std::cmp::max(ans, insert_val);
}
}

return ans;
}
}