-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a2aa574
commit 6707349
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
|
||
|
||
} | ||
} |