We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My O(n) solution in C++. Here is my idea:
1. For each value of t[i], count all sastified starting points then store in an array.
2. Search for max element in array then return the index.
To store and search effciently, you may try the problem Array Manipulation in Data structure - hard - array
intsolve(vector<int>t){intn=t.size();/* n < 10^5 Must move to heap memory */intarr[n+1]={0};for(inti=0;i<n;++i){if(t[i]-i>0){/* t[i] > i The start point is included in (i+1,n - (t[i]-i)) Add 1 in the count array when go into the interval Remove 1 when go out the interval */arr[i+1]+=1;arr[n-(t[i]-i)+1]-=1;}else{/* t[i] <= i The start point is included in (0,i - t[i]) and (i+1,n-1) Add 1 in the count array when go into the interval Remove 1 when go out the interval */arr[0]+=1;arr[i-t[i]+1]-=1;arr[i+1]+=1;arr[n]-=1;}}intindex=0;intcount=0;intmax=0;for(inti=0;i<n;++i){count+=arr[i];if(count>max){max=count;index=i+1;}}returnindex;}
Kindergarten Adventures
You are viewing a single comment's thread. Return to all comments →
My O(n) solution in C++. Here is my idea: 1. For each value of t[i], count all sastified starting points then store in an array. 2. Search for max element in array then return the index. To store and search effciently, you may try the problem Array Manipulation in Data structure - hard - array