Advertisement
goshansmails

Untitled

Mar 14th, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6. /*
  7.  *
  8.  * no changes
  9.  *
  10. int maxOnes(const vector<int>& v) {
  11.     int n = v.size();
  12.     int left = 0;
  13.     int right = 0;
  14.     int ans = 0;
  15.     while (right < n) {
  16.         left = right;
  17.         while (right < n && v[right] == 1) {
  18.             right++;
  19.         }
  20.         ans = max(ans, right - left);
  21.         right++;
  22.     }
  23.     return ans;
  24. }
  25.  */
  26.  
  27. int maxOnes(const vector<int>& v) {
  28.     size_t n = v.size();
  29.     // n > 0
  30.  
  31.     // only ones no zeros
  32.     if (count(v.begin(), v.end(), 1) == n) {
  33.         return n - 1;
  34.     }
  35.  
  36.     int ans = -1;
  37.     int cur_zero_idx = -1;
  38.     bool has_zero = false;
  39.     int left = 0;
  40.     int right = 0;
  41.  
  42.     while (right < n) {
  43.         while (right < n && v[right] == 1) {
  44.             ++right;
  45.         }
  46.         if (right < n) {
  47.             has_zero = true;
  48.             cur_zero_idx = right;
  49.             right++; // delete zero
  50.             while (right < n && v[right] == 1) {
  51.                 ++right;
  52.             }
  53.         }
  54.         ans = max(ans, right - left);
  55.         if (has_zero) {
  56.             left = right = cur_zero_idx + 1; // next pos after current zero
  57.             has_zero = false;
  58.         }
  59.     }
  60.  
  61.     return ans;
  62. }
  63.  
  64. int main() {
  65.  
  66.     cout << maxOnes({0, 0, 1, 0, 1, 0, 0, 0, 0}) << endl;
  67.     cout << maxOnes({1, 1, 1, 1}) << endl;
  68.     cout << maxOnes({0, 0, 1, 1}) << endl;
  69.     cout << maxOnes({1, 1, 1, 1, 0, 0, 0, 0, 0}) << endl;
  70.     cout << maxOnes({0, 0, 0}) << endl;
  71.     cout << maxOnes({1}) << endl;
  72.     cout << maxOnes({1, 1, 1, 0, 1, 1}) << endl;
  73.     cout << maxOnes({1,1,1,1, 0,0,0,0,0,1,1,1,1,1,1}) << endl;
  74.     cout << maxOnes({1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1}) << endl;
  75.     cout << maxOnes({1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1}) << endl;
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement