Max Consecutive Ones (Kotlin) Solutions

I am currently learning Data structure and Algorithms deeper in kotlin and I decided to start with Leetcode.

The problem

Given a binary array nums, return the maximum number of consecutive 1's in the array.

Example 1:

Input: nums = [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. The maximum number of consecutive 1s is 3.


The first step is to understand the problem and think of the best possible way to solve it. what Leetcode wants you to do is get the highest number of consecutive (following each other continuously) 1`s in the given array


nums = [1,1,0,1,1,1] the correct answer is 3

nums = [1,1,0,1,1,1,1] the correct answer is 4

nums = [1,0,0,1,1,0] the correct answer is 2

Kotlin Code

Code Explanation

there are so many ways to solve a problem, but this is how I solved mine,

Firstly, you have to create two variables that will hold the largest number and get the count for the current value.

which I called current and largest and assign 0 to them.

var current = 0
var largest = 0

Secondly, you will loop through the array of 0 and 1 array, get the elements of the array and check for the value 0.

for (u in ty) {
if (u == 0) {

if you find 0, then set the current to 0, and if not zero(0) then increment the current by 1.

current = 0
} else {

Thirdly, Before ending the current iteration of the loop, you will check if the current is greater than the largest.
If yes, set currentto largest.

if (current > largest) largest = current

Then return the largest

Thanks for reading.

A software engineer with considerable experience in mobile development, native Android, and IOS development(Xcode), flutter dev, technical writing and community

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store