813. Largest Sum of Averages

We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?

Note that our partition must use every number in A, and that scores are not necessarily integers.

Example:
Input: 
A = [9,1,2,3,9]
K = 3
Output: 20
Explanation: 
The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.

 

Note:

  • 1 <= A.length <= 100.
  • 1 <= A[i] <= 10000.
  • 1 <= K <= A.length.
  • Answers within 10^-6 of the correct answer will be accepted as correct.

Rust Solution

struct Solution;

use std::collections::HashMap;

impl Solution {
    fn largest_sum_of_averages(a: Vec<i32>, k: i32) -> f64 {
        let n = a.len();
        let k = k as usize;
        let mut memo: HashMap<(usize, usize), f64> = HashMap::new();
        Self::dp(n, k, &mut memo, &a)
    }
    fn dp(n: usize, k: usize, memo: &mut HashMap<(usize, usize), f64>, a: &[i32]) -> f64 {
        if n == 0 {
            0.0
        } else {
            if let Some(&res) = memo.get(&(n, k)) {
                return res;
            }
            let res = if k == 1 {
                a[0..n].iter().sum::<i32>() as f64 / n as f64
            } else {
                let mut last = 0.0;
                let mut res: f64 = 0.0;
                for i in (0..n).rev() {
                    last += a[i] as f64;
                    let avg = last as f64 / (n - i) as f64;
                    res = res.max(avg + Self::dp(i, k - 1, memo, a));
                }
                res
            };
            memo.insert((n, k), res);
            res
        }
    }
}

#[test]
fn test() {
    use assert_approx_eq::assert_approx_eq;
    let a = vec![9, 1, 2, 3, 9];
    let k = 3;
    let res = 20.0;
    assert_approx_eq!(Solution::largest_sum_of_averages(a, k), res);
}

Having problems with this solution? Click here to submit an issue on github.