#include <iostream> using namespace std; int main() { cout Type to search LeetCode solutions Introduction Solutions 1 - 50 1Two Sum – Medium 2 Add Two Numbers – Medium 3 Longest Substring Without Repeating Characters 4 Median of Two Sorted Arrays 5 Longest Palindromic Substring 6 ZigZag Conversion – Easy 7 Reverse Integer – Easy 8 String to Integer (atoi) – Easy 9 Palindrome Number – Easy 10 Regular Expression Matching 11 Container With Most Water – Medium 12 Integer to Roman – Medium 13 Roman to Integer – Easy 14 Longest Common Prefix – Easy 15 3Sum – Medium 16 3Sum Closest – Medium 17 Letter Combinations of a Phone Number – Medium 18 4Sum – Medium 19 Remove Nth Node From End of List – Easy 20 Valid Parentheses – Easy 21 Merge Two Sorted Lists – Easy 22 Generate Parentheses – Medium 23 Merge k Sorted Lists 24 Swap Nodes in Pairs – Medium 25 Reverse Nodes in k-Group 26 Remove Duplicates from Sorted Array – Easy 27 Remove Element – Easy 28 Implement strStr() – Easy 29 Divide Two Integers – Medium 31 Next Permutation – Medium 33 Search in Rotated Sorted Array – Hard 34 Search for a Range – Medium 35 Search Insert Position – Medium 36 Valid Sudoku – Easy 37 Sudoku Solver 38 Count and Say – Easy 39 Combination Sum – Medium 40 Combination Sum II – Medium 42 Trapping Rain Water 43 Multiply Strings – Medium 44 Wildcard Matching 46 Permutations – Medium 47 Permutations II – Medium 48 Rotate Image – Medium 49 Group Anagrams – Medium 50 Pow(x, n) – Medium Solutions 51 - 100 53 Maximum Subarray – Medium 54 Spiral Matrix – Medium 55 Jump Game – Medium 56 Merge Intervals 57 Insert Interval 58 Length of Last Word – Easy 59 Spiral Matrix II – Medium 60 Permutation Sequence – Medium 61 Rotate List – Medium 62 Unique Paths – Medium 63 Unique Paths II – Medium 64 Minimum Path Sum – Medium 65 Valid Number 66 Plus One – Easy 67 Add Binary – Easy 68 Text Justification 69 Sqrt(x) – Medium 70 Climbing Stairs – Easy 71 Simplify Path – Medium 73 Set Matrix Zeroes – Medium 74 Search a 2D Matrix – Medium 75 Sort Colors – Medium 76 Minimum Window Substring 77 Combinations – Medium 78 Subsets – Medium 79 Word Search – Medium 80 Remove Duplicates from Sorted Array II – Medium 81 Search in Rotated Sorted Array II 82 Remove Duplicates from Sorted List II – Medium 83 Remove Duplicates from Sorted List – Easy 85 Maximal Rectangle 86 Partition List – Medium 88 Merge Sorted Array 89 Gray Code – Medium 90 Subsets II – Medium 91 Decode Ways – Medium 92 Reverse Linked List II – Medium 93 Restore IP Addresses – Medium 94 Binary Tree Inorder Traversal – Medium 95 Unique Binary Search Trees II – Medium 98 Validate Binary Search Tree Solutions 101 - 150 101 Symmetric Tree – Easy 102 Binary Tree Level Order Traversal – Easy 103 Binary Tree Zigzag Level Order Traversal 104 Maximum Depth of Binary Tree – Easy 105 Construct Binary Tree from Preorder and Inorder Traversal – Medium 106 Construct Binary Tree from Inorder and Postorder Traversal – Medium 107 Binary Tree Level Order Traversal II – Easy 108 Convert Sorted Array to Binary Search Tree – Medium 109 Convert Sorted List to Binary Search Tree – Medium 110 Balanced Binary Tree – Easy 111Minimum Depth of Binary Tree – Easy 112 Path Sum – Easy 113 Path Sum II – Medium 114 Flatten Binary Tree to Linked List – Medium 116 Populating Next Right Pointers in Each Node – Medium 117 Populating Next Right Pointers in Each Node II 118 Pascal’s Triangle – Easy 119 Pascal’s Triangle II – Medium 120 Triangle – Medium 121 Best Time to Buy and Sell Stock – Medium 122 Best Time to Buy and Sell Stock II – Medium 123 Best Time to Buy and Sell Stock III – Hard 125 Valid Palindrome – Easy 127 Word Ladder – Medium 128 Longest Consecutive Sequence 129 Sum Root to Leaf Numbers – Medium 130 Surrounded Regions – Medium 131 Palindrome Partitioning – Medium 132 Palindrome Partitioning II – Hard 133 Clone Graph – Medium 134 Gas Station – Medium 136 Single Number – Medium 137 Single Number II – Medium 138 Copy List with Random Pointer 139 Word Break – Medium 140 Word Break II – Hard 141 Linked List Cycle – Medium 142 Linked List Cycle II – Medium 143 Reorder List – Medium 144 Binary Tree Preorder Traversal – Medium 145 Binary Tree Postorder Traversal – Hard 146 LRU Cache – Hard 147 Insertion Sort List – Medium 148 Sort List 149 Max Points on a Line 150 Evaluate Reverse Polish Notation – Medium Solutions 151 - 200 151 Reverse Words in a String – Medium 152 Maximum Product Subarray – Medium 153 Find Minimum in Rotated Sorted Array – Medium 155 Min Stack – Easy 156 Binary Tree Upside Down – Medium 157 Read N Characters Given Read4 – Easy 158 Read N Characters Given Read4 II – Call multiple times Add to List QuestionEditorial Solution – Hard 159 Longest Substring with At Most Two Distinct Characters 160 Intersection of Two Linked Lists – Easy 161 One Edit Distance – Medium 162 Find Peak Element – Medium 163 Missing Ranges 165 Compare Version Numbers 166 Fraction to Recurring Decimal 167 Two Sum II – Input array is sorted – Medium 168 Excel Sheet Column Title – Easy 169 Majority Element – Easy 170 Two Sum III – Data structure design – Easy 171 Excel Sheet Column Number – Easy 172 Factorial Trailing Zeroes – Easy 173 Binary Search Tree Iterator – Medium 179 Largest Number – Medium 186 Reverse Words in a String II – Medium 187 Repeated DNA Sequences – Medium 189 Rotate Array – Easy 190 Java: Reverse Bits – Easy 191 Number of 1 Bits – Easy 198 House Robber – Easy 199 Binary Tree Right Side View – Medium 200 Number of Islands – Medium Solutions 201 - 250 201 LeetCode Java : Bitwise AND of Numbers Range – Medium 202 LeetCode Java: Happy Number – Easy 203 LeetCode Java: Remove Linked List Elements – Easy 204 LeetCode Java: Count Primes – Easy 205 LeetCode Java: Isomorphic Strings – Easy 206 LeetCode Java: Reverse Linked List -Easy 207 LeetCode Java: Course Schedule – Medium 208 LeetCode Java: Implement Trie (Prefix Tree) – Medium 209 LeetCode Java : Minimum Size Subarray Sum – Medium 210 LeetCode Java: Course Schedule II – Medium 211 LeetCode Java: Add and Search Word – Data structure design – Medium 212 Word Search II 213 House Robber II – Medium 214 Shortest Palindrome 215 Kth Largest Element in an Array – Medium 216 Combination Sum III – Medium 217 Contains Duplicate – Easy 218 The Skyline Problem 219 Contains Duplicate II – Medium 220 Contains Duplicate III – Medium 221 Maximal Square – Medium 222 Count Complete Tree Nodes – Medium 223 Rectangle Area – Easy 224 Basic Calculator 225 Implement Stack using Queues – Easy 226 Invert Binary Tree – Easy 227 Basic Calculator II – Medium 228 Summary Ranges – Medium 229 Majority Element II – Medium 230 Kth Smallest Element in a BST – Medium 231 Power of Two – Easy 232 Implement Queue using Stacks – Easy 234 Palindrome Linked List – Easy 235 Lowest Common Ancestor of a Binary Search Tree – Easy 236 Lowest Common Ancestor of a Binary Tree – Medium 237 Delete Node in a Linked List – Easy 238 Product of Array Except Self – Medium 239 Sliding Window Maximum 240 Search a 2D Matrix II – Medium 241 Different Ways to Add Parentheses – Medium 242 Valid Anagram – Easy 243 Shortest Word Distance – Easy 244 Shortest Word Distance II – Medium 245 Shortest Word Distance III – Medium 246 Strobogrammatic Number – Easy 247 Strobogrammatic Number II 248 LeetCode Java: Different Ways to Add Parentheses – Hard 249 LeetCode Java: Group Shifted Strings – Easy 250 LeetCode Java: Count Univalue Subtrees – Medium Solutions 251 - 300 251 Flatten 2D Vector 252 LeetCode Java: Meeting Rooms – Easy 253 Meeting Rooms II - Medium 254 Factor Combinations - Medium 255 Verify Preorder Sequence in Binary Search Tree - Medium 256 Paint House - Medium 257 Binary Tree Paths - Easy 258 Add Digits - Easy 259 3Sum Smaller 260 Single Number III 261 Graph Valid Tree 263 Ugly Number 264 Ugly Number II 266 Palindrome Permutation 267 Palindrome Permutation II 268 Missing Number 269 Alien Dictionary 270 Closest Binary Search Tree Value 271 Encode and Decode Strings 272 Closest Binary Search Tree Value II 273 Integer to English Words 274 H-Index 275 H-Index II 276 Paint Fence 277 Find the Celebrity 278 First Bad Version 279 Perfect Squares 280 Wiggle Sort 281 Zigzag Iterator 282 Expression Add Operators 283 Move Zeroes 284 Peeking Iterator 285 Inorder Successor in BST 286 Walls and Gates 288 Unique Word Abbreviation 289 Game of Life 290 Word Pattern 291 Word Pattern II 292 Nim Game 293 Flip Game 294 Flip Game II 295 Find Median from Data Stream 297 Serialize and Deserialize Binary Tree 298 Binary Tree Longest Consecutive Sequence 299 Bulls and Cows Solutions 301 - 350 301 Remove Invalid Parentheses 302 Smallest Rectangle Enclosing Black Pixels 303 Range Sum Query - Immutable 304 Range Sum Query 2D - Immutable 305 Number of Islands II 306 Additive Number 307 Range Sum Query - Mutable 308 Range Sum Query 2D - Mutable 309 Best Time to Buy and Sell Stock with Cooldown 310 Minimum Height Trees 311 Sparse Matrix Multiplication 312 Burst Balloons 313 Super Ugly Number 314 Binary Tree Vertical Order Traversal 315 Count of Smaller Numbers After Self 316 Remove Duplicate Letters 317 Shortest Distance from All Buildings 318 Maximum Product of Word Lengths 319 Bulb Switcher 320 Generalized Abbreviation 321 Create Maximum Number 322 Coin Change 323 Number of Connected Components in an Undirected Graph 324 Wiggle Sort II 325 Maximum Size Subarray Sum Equals k 326 Power of Three 327 Count of Range Sum 328 Odd Even Linked List 329 Longest Increasing Path in a Matrix 330 Patching Array 331 Verify Preorder Serialization of a Binary Tree 332 Reconstruct Itinerary 333 Largest BST Subtree 334 Increasing Triplet Subsequence 336 Palindrome Pairs 337 House Robber III 338 Counting Bits 339 Nested List Weight Sum 340 Longest Substring with At Most K Distinct Characters 341 Flatten Nested List Iterator 342 Power of Four 343 Integer Break 344 Reverse String 345 Reverse Vowels of a String 346 Moving Average from Data Stream 347 Top K Frequent Elements 348 Design Tic-Tac-Toe 349 Intersection of Two Arrays 350 Intersection of Two Arrays II Solutions 351 - 400 351 Android Unlock Patterns 353 Design Snake Game 354 Russian Doll Envelopes 355 Design Twitter 356 Line Reflection 357 Count Numbers with Unique Digits 358 Rearrange String k Distance Apart 359 Logger Rate Limiter 360 Sort Transformed Array 361 Bomb Enemy 362 Design Hit Counter 363 Max Sum of Rectangle No Larger Than K 364 Nested List Weight Sum II 365 Water and Jug Problem 366 Find Leaves of Binary Tree 367 Valid Perfect Square 368 Largest Divisible Subset 369 Plus One Linked List 370 Range Addition 371 Sum of Two Integers 372 Super Pow 373 Find K Pairs with Smallest Sums 374 Guess Number Higher or Lower 375 Guess Number Higher or Lower II 377 Combination Sum IV 378 Kth Smallest Element in a Sorted Matrix 379 Design Phone Directory 380 Insert Delete GetRandom O(1) 382 Linked List Random Node 388 Longest Absolute File Path 389 Find the Difference 391 Perfect Rectangle 393 UTF-8 Validation 394 Decode String 397 Integer Replacement 398 Random Pick Index 399 Evaluate Division 400 Nth Digit Solutions 401 - 450 401 Binary Watch 402 Remove K Digits 404 Sum of Left Leaves 406 Queue Reconstruction by Height 407 Trapping Rain Water II 408 Valid Word Abbreviation 409 Longest Palindrome 411 Minimum Unique Word Abbreviation 415 Add Strings 417 Pacific Atlantic Water Flow 418 Sentence Screen Fitting 421 Maximum XOR of Two Numbers in an Array 422 Valid Word Square 425 Word Squares 444 Sequence Reconstruction 447 Number of Boomerangs 448 Find All Numbers Disappeared in an Array 404 Sum of Left Leaves 410 Split Array Largest Sum 432 All O`one Data Structure 437 Path Sum III 450 Delete Node in a BST Solutions 451 - 500 451 Sort Characters By Frequency 459 Repeated Substring Pattern 460 LFU Cache 461 Hamming Distance 463 Island Perimeter 465 Optimal Account Balancing 469 Convex Polygon 471 Encode String with Shortest Length 474 Ones and Zeroes 475 Heaters 480 Sliding Window Median 481 Magical String 482 License Key Formatting 483 Smallest Good Base 484 Find Permutation 485 Max Consecutive Ones 486 Predict the Winner 487 Max Consecutive Ones II 490 The Maze 493 Reverse Pairs 494 Target Sum 498 Diagonal Traverse Solutions 501 - 550 501 Find Mode in Binary Search Tree 503 Next Greater Element II 505 The Maze II 506 Relative Ranks 514 Freedom Trail 515 Find Largest Value in Each Tree Row 520 Detect Capital 521 Longest Uncommon Subsequence I 522 Longest Uncommon Subsequence II 523 Continuous Subarray Sum 524 Longest Word in Dictionary through Deleting 525 Contiguous Array 526 Beautiful Arrangement 527 Word Abbreviation 530 Minimum Absolute Difference in BST 531 Lonely Pixel I 533 Lonely Pixel II 534 Design TinyURL 535 Encode and Decode TinyURL 541 Reverse String II 542 01 Matrix 543 Diameter of Binary Tree 544 Output Contest Matches 545 Boundary of Binary Tree 549 Binary Tree Longest Consecutive Sequence II 516 Longest Palindromic Subsequence Solutions 551 - 600 551 Student Attendance Record I 552 Student Attendance Record II 560 Subarray Sum Equals K 562 Longest Line of Consecutive One in Matrix 568 Maximum Vacation Days 569 Median Employee Salary 554 Brick Wall Solutions 601 - 650 621 Task Scheduler 633 Sum of Square Numbers 636 Exclusive Time of Functions 637 Average of Levels in Binary Tree 639 Decode Ways II 642 Design Search Autocomplete System 647 Palindromic Substrings 648 Replace Words Solutions 651 - 700 653 Two Sum IV - Input is a BST 689 Maximum Sum of 3 Non-Overlapping Subarrays 670 Maximum Swap 671 Second Minimum Node In a Binary Tree 680 Valid Palindrome II 690 Employee Importance 692 Top K Frequent Words 698 Partition to K Equal Sum Subsets 699 Falling Squares Solutions 701 - 750 714 Best Time to Buy and Sell Stock with Transaction Fee 716 Max Stack 744 Find Smallest Letter Greater Than Target 730 Count Different Palindromic Subsequences 733 Flood Fill 735 Asteroid Collision Best Time to Buy and Sell Stock Powered by GitBook 487 Max Consecutive Ones II Problem: Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. Example 1: Input: [1,0,1,1,0] Output: 4 Explanation: Flip the first zero will get the the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4. Note: The input array will only contain 0 and 1. The length of input array is a positive integer and will not exceed 10,000 Follow up: What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently? Solutions: public class Solution { public int findMaxConsecutiveOnes(int[] nums) { int[] count = new int[2]; int index = 0; int max = 0; boolean zero = false; for (int i = 0; i < nums.length; i ++) { if (nums[i] == 1) { count[index] ++; max = Math.max(max, count[0] + count[1]); } else { zero = true; index = index ^ 1; count[index] = 0; } } if (zero == true) { max ++; } return max; } } public class Solution { public int findMaxConsecutiveOnes(int[] nums) { int res = 0, cur = 0, cnt = 0; for (int i = 0; i < nums.length; i ++) { cnt ++; if (nums[i] == 0) { cur = cnt; cnt = 0; } res = Math.max(res, cnt + cur); } return res;
Write, Run & Share C++ code online using OneCompiler's C++ online compiler for free. It's one of the robust, feature-rich online compilers for C++ language, running on the latest version 17. Getting started with the OneCompiler's C++ compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C++
and start coding!
OneCompiler's C++ online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Enter name:";
getline (cin, name);
cout << "Hello " << name;
return 0;
}
C++ is a widely used middle-level programming language.
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
//code
}
else {
//code
}
You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.
Switch is an alternative to If-Else-If ladder.
switch(conditional-expression){
case value1:
// code
break; // optional
case value2:
// code
break; // optional
......
default:
code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while (condition) {
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. Function gets run only when it is called.
return_type function_name(parameters);
function_name (parameters)
return_type function_name(parameters) {
// code
}