carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode643:子数组最大平均数 I(maximum-average-subarray-i) #116

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题分析

给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。

请你找出平均数最大且 长度为 k 的连续子数组,并输出该最大平均数。

任何误差小于 10-5 的答案都将被视为正确答案。

 

示例 1:

输入:nums = [1,12,-5,-6,50,3], k = 4 输出:12.75 解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75 示例 2:

输入:nums = [5], k = 1 输出:5.00000  

提示:

n == nums.length 1 <= k <= n <= 105 -104 <= nums[i] <= 104

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/maximum-average-subarray-i

carloscn commented 1 year ago

问题分析


static int64_t sum(int64_t *array, size_t sz)
{
    int64_t sum = 0;
    size_t i = 0;

    for (i = 0; i < sz; i ++) {
        sum += array[i];
    }

    return sum;
}

static int32_t max_average(int64_t *array, size_t sz, size_t k, int64_t *average_out)
{
    int32_t ret = 0;
    int64_t ave = 0;
    int64_t max_average = 0;
    size_t i = 0, j = 0;

    UTILS_CHECK_PTR(array);
    UTILS_CHECK_LEN(sz);
    UTILS_CHECK_LEN(k);
    UTILS_CHECK_PTR(average_out);

    for (i = 0; i < sz - k; i ++) {
        ave = sum(array + i, k);
        max_average = (ave > max_average) ? ave : max_average;
    }

    *average_out = max_average / k;

finish:
    return ret;
}
carloscn commented 1 year ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/array/39_maximum-average-subarray-i_643.c https://github.com/carloscn/structstudy/blob/master/rust_programming/array/src/n39_maximum_average_subarray_i_643.rs

result:

image