Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 1004 #234

Merged
merged 1 commit into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/problem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub mod p0724_find_pivot_index;
pub mod p0739_daily_temperatures;
pub mod p0912_sort_an_array;
pub mod p0926_flip_string_to_monotone_increasing;
pub mod p1004_max_consecutive_ones_iii;
pub mod p1016_binary_string_with_substrings_representing_1_to_n;
pub mod p1054_distant_barcodes;
pub mod p1186_maximum_subarray_sum_with_one_deletion;
Expand Down
73 changes: 73 additions & 0 deletions src/problem/p1004_max_consecutive_ones_iii.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the
// array if you can flip at most k 0's.

// Example 1:

// Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
// Output: 6
// Explanation: [1,1,1,0,0,1,1,1,1,1,1]
// Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
// Example 2:

// Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
// Output: 10
// Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
// Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.

// Constraints:

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

// problem: https://leetcode.com/problems/max-consecutive-ones-iii/

// submission codes start here
pub struct Solution {}

impl Solution {
pub fn longest_ones(nums: Vec<i32>, k: i32) -> i32 {
let mut l = 0;
let mut r = 0;
let mut z = 0;
let mut ret = 0;
while r < nums.len() {
if nums[r] == 0 {
z += 1;
}
while l <= r && z > k {
if nums[l] == 0 {
z -= 1;
}
l += 1;
}
ret = std::cmp::max(ret, r as i32 - l as i32 + 1);
r += 1;
}

ret
}
}

// submission codes end

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_1004() {
assert_eq!(Solution::longest_ones(vec![0, 0, 0], 0), 0);
assert_eq!(
Solution::longest_ones(vec![1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], 2),
6
);
assert_eq!(
Solution::longest_ones(
vec![0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1],
3
),
10
);
}
}