1.1 Longest Consecutive 1s
Assumption: given array is not null
Input: int[] array of 0s and 1s
Output: int the length of the longest consecutive 1s in the array
Solution: dp[i] represents w/in [0,i] the longest consecutive 1s
= dp[i - 1] + 1 if array[i] = 1, else = 0
public int longestOnes(int[] array) {
int curMax = 0;
int length = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 1) {
if (i == 0 || array[i - 1] == 0) {
curMax = 1;
} else {
curMax++;
}
}
length = Math.max(curMax, length);
}
return length;
}
Last updated
Was this helpful?