carloscn / structstudy

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

leetcode485:最大连续1的个数(max-consecutive-ones) #106

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给定一个二进制数组 nums , 计算其中最大连续 1 的个数。

示例 1: 输入:nums = [1,1,0,1,1,1] 输出:3 解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.

示例 2: 输入:nums = [1,0,1,1,0,1] 输出:2   提示: 1 <= nums.length <= 105 nums[i] 不是 0 就是 1.

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/max-consecutive-ones

carloscn commented 1 year ago

问题分析

static int32_t max_consec(char *array, size_t len, size_t *out)
{
    int32_t ret = 0;
    size_t i = 0;
    size_t count = 0;
    size_t max_count = 0;

    UTILS_CHECK_PTR(array);
    UTILS_CHECK_PTR(out);
    UTILS_CHECK_LEN(len);

    for (i = 0; i < len; i ++) {
        if (1 == array[i]) {
            count ++;
        } else if (0 == array[i]) {
            count = 0;
        } else {
            ret = 1;
            LOG("input error\n");
            goto finish;
        }

        if (max_count <= count) {
            max_count = count;
        }
    }

    *out = max_count;

finish:
    return ret;
}
carloscn commented 1 year ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/array/35_max-consecutive-ones_485.c

result:

image