What is the Time-Complexity of following code? Given array is permutation of (1 to n).

Правка en2, от CodeKar, 2022-12-25 10:36:07

include <bits/stdc++.h>

using namespace std; typedef vector vi; void solve() { int n; cin>>n; vi v(n); for(int i=0;i<n;i++)cin>>v[i];

vi ans(n+1,0);

for(int i=0;i<n;i++)
{
    ans[i] = 1e9;
    for(int j=i-1;j>=0;j--)
    {
       if(ans[i]<i-j)
         break;

       ans[i] = min(ans[i],abs(v[i]-v[j])+(abs(i-j)));
    }

    for(int j=i+1;j<n;j++)
    {
       if(ans[i] < j-i)
       {
         break;
       }

       ans[i] = min(ans[i],abs(v[i]-v[j])+abs(i-j));
    }

    cout<<ans[i]<<" ";
}

} signed main() { int T; T=1; cin>>T; while(T--) { solve(); } }

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en2 Английский CodeKar 2022-12-25 10:36:07 40
en1 Английский CodeKar 2022-12-25 10:34:59 658 The given code is working for 2<=N<=2e5. According to me it should be O(n^2) but it passed the given constraint. Given that v is permutation of (1 to n). (published)