LeetCode Exercise

Logo

This is my LeetCode exercise.
You can see all question I did here.

View the Project on GitHub YaoyuanHsu/LeetCode_Exercise

tags: leetcode medium Array Prefix Sum

2256. Minimum Average Difference

Description

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:

Examples

Example 1:

Input: nums = [2,5,3,9,5,3]
Output: 3
Explanation:

Example 2:

Input: nums = [0]
Output: 0
Explanation:
The only index is 0 so return 0.
The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.

Constraints:

Code

int minimumAverageDifference(int* nums, int numsSize) {
    if (numsSize == 1)
        return 0;
    long* sum = calloc(numsSize, sizeof(long));
    int index = 0, min = INT_MAX, tmp = 0;
    // Collect all summation
    sum[0] = nums[0];
    for (int i = 1; i < numsSize; i++)
        sum[i] = sum[i - 1] + nums[i];
    for (int i = 0; i < numsSize; i++) {
        // Calculate all average difference
        tmp = abs(sum[i] / (i + 1) -
            ((numsSize - i - 1) ? ((sum[numsSize - 1] - sum[i]) / (numsSize - i - 1)) : 0));
        // Update minimum and index
        if (tmp < min) {
            min = tmp;
            index = i;
        }
    }
    return index;
}

Complexity

Space Time
$O(N)$ $O(N)$

Result