Comments

Thanks.. But consider a case when ans[i]<ans[i+1]..so we make ans[i]=ans[i+1] in the last line of code.. My question is why can't ans[i]>ans[i+1] as we have not calculated ans[i(len)] for every pair i,j where abs(i-j)+1 =len

With reference to your last line of code

for(int i=n-1; i>0; i--) ans[i]=max(ans[i],ans[i+1]);

how do we make sure that ans[i] is not greater than max(ans[i],ans[i+1]) for all i