#2256
Medium Algorithms Minimum average difference
Array Prefix Sum
43.8% acceptance
Feb 25, 2026
1569
182
You are given a 0-indexed integer array nums of length n.
The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.
Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.
Note:
The absolute difference of two numbers is the absolute value of their difference.
The average of n elements is the sum of the n elements divided (integer division) by n.
The average of 0 elements is considered to be 0.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_average_difference(nums: Vec<i32>) -> i32 {
let n = nums.len() as i64;
let total: i64 = nums.iter().map(|&x| x as i64).sum();
let mut prefix = 0i64;
let mut min_diff = i64::MAX;
let mut ans = 0usize;
for i in 0..nums.len() {
prefix += nums[i] as i64;
let left_avg = prefix / (i as i64 + 1);
let right_cnt = n - i as i64 - 1;
let right_avg = if right_cnt == 0 { 0 } else { (total - prefix) / right_cnt };
let diff = (left_avg - right_avg).abs();
if diff < min_diff {
min_diff = diff;
ans = i;
}
}
ans as i32
}
}