Leetcode - max-consecutive-ones
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