Skip to content

Commit

Permalink
Create longestsubarray.java
Browse files Browse the repository at this point in the history
  • Loading branch information
abhishektripathi66 authored Jul 8, 2024
1 parent a2aa574 commit 6707349
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Leetcode/longestsubarray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//**

Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.



Example 1:

Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:

Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:

Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.


Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.

**//

class longestsubarray {
public int longestSubarray(int[] nums) {
int count = 0, prevCount = 0, res = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
count++;
} else {
res = Math.max(res, count + prevCount);
prevCount = count;
count = 0;
}
}

res = Math.max(res, count + prevCount);
return res == nums.length ? res - 1 : res;


}
}

0 comments on commit 6707349

Please sign in to comment.