1 #define pb push_back 2 #define maxSize 3939 3 #define _for(i,a,b) for(int i = (a);i < (b);i ++) 4 5 class Solution 6 { 7 public: 8 int longestOnes(vector<int>& A, int K) 9 { 10 vector<int> v; 11 for(int i = 0;i < A.size();) 12 { 13 int cnt = 0; 14 while(i < A.size() && A[i]==1) 15 { 16 cnt ++; 17 i ++; 18 } 19 v.pb(cnt); 20 cnt = 0; 21 while(i < A.size() && A[i]==0) 22 { 23 cnt ++; 24 i ++; 25 } 26 v.pb(cnt); 27 } 28 int rnt = 0; 29 for(int i = 0;i < v.size();i += 2) 30 { 31 int tmpk = K; 32 int tmprnt = v[i]; 33 int j = i; 34 while(tmpk) 35 { 36 if(tmpk>=v[j+1]&&j+2<v.size()) 37 { 38 tmprnt += v[j+2]+v[j+1]; 39 tmpk -= v[j+1]; 40 j += 2; 41 } 42 else 43 { 44 tmprnt += tmpk; 45 break; 46 } 47 48 } 49 rnt = max(rnt,tmprnt); 50 } 51 int sz = A.size(); 52 return min(rnt,sz); 53 } 54 };
这题也是乱搞,没有前几周的Ⅱ难,只要对每个连续的数字1块进行遍历,看看以他为头能往后延长多少就行,算是个贪心吧。这么贪的理由是,最后形成的最长1串必定包含某一个原来的数字1块,并且以这一个数字1块开头。