diff options
author | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
commit | 7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch) | |
tree | eb7a24ee2067f92245c57bb118e85a1baf15df50 /other/longest_subarr_ones.cpp | |
parent | 5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff) | |
download | leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip |
chore: move cpp and rust code to directory
Diffstat (limited to 'other/longest_subarr_ones.cpp')
-rw-r--r-- | other/longest_subarr_ones.cpp | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/other/longest_subarr_ones.cpp b/other/longest_subarr_ones.cpp new file mode 100644 index 0000000..35f2353 --- /dev/null +++ b/other/longest_subarr_ones.cpp @@ -0,0 +1,31 @@ +// 1493. Longest Subarray of 1's After Deleting One Element +#include "leetcode.h" + +/* + * 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. + */ + +class Solution { +public: + int longestSubarray(vector<int> &nums) { + int ans = 0; + for (int i = 0, j = 0, skip = 0; i < nums.size(); ++i) { + skip += !nums[i]; + if (skip > 1) + skip -= !nums[j++]; + ans = max(ans, i - j); + } + return ans; + } +}; + +int main() { + Solution obj; + vector<int> n1 = {1, 1, 0, 1}, n2 = {0, 1, 1, 1, 0, 1, 1, 0, 1}, + n3 = {1, 1, 1}; + printf("%d\n", obj.longestSubarray(n1)); // expect: 3 + printf("%d\n", obj.longestSubarray(n2)); // expect: 5 + printf("%d\n", obj.longestSubarray(n3)); // expect: 2 +} |