Leetcode - subarray-sums-divisible-by-k
Leetcode - rotting-oranges

Leetcode - max-consecutive-ones

violet posted @ Feb 27, 2020 08:31:17 AM in 算法 with tags Algorithm array Golang ruby , 229 阅读

https://leetcode.com/problems/max-consecutive-ones/

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

Use two pointers to iterate the array.

func findMaxConsecutiveOnes(nums []int) int {
    sum := math.MinInt32
    i := 0
    j := 0
    for i < len(nums){
        tmpSum := 0
        j = i
        for j < len(nums) && nums[j] == 1 {
            tmpSum++
            j++
        }
        if sum < tmpSum {
            sum = tmpSum
        }
        i = j + 1
    }
    return sum
}
# @param {Integer[]} nums
# @return {Integer}
def find_max_consecutive_ones(nums)
    sum = -1
    i = 0
    j = 0
    while i < nums.length
        tmp_sum = 0
        j = i
        while j < nums.length && nums[j] == 1
            tmp_sum += 1
            j += 1
        end
        if sum < tmp_sum
            sum = tmp_sum
        end
        i = j + 1
    end
    return sum
end

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter