JavaScript solution


  • 0
    L

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

    I have two programme:

    • solution A: ergodic the array; if item does't equal 0, variable 'result' plus 1. else push result into a new array, and result equal 0. After ergodic, find out the max of the new array
    • solution B: turn the array to a string, and split with 0, now the array is a new array and its items are 1s, the max of item's length is the last result.

    Here is the code of solution B:

    /**
     * @param {number[]} nums
     * @return {number}
     */
    var findMaxConsecutiveOnes = function(nums) {
        var result = 0
        nums = nums.join('').split('0')
        for(var i=0; i<nums.length; i++) {
            if(result < nums[i].length) {
                result = nums[i].length
            }
        }
        return result
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.