fork download
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. int L[]={1,3,5,7,4,6,10};
  8. int S=7;
  9. int H[15];
  10. /*
  11.   Construct hash table of M elements where M is the maximum number possible
  12.   */
  13. for(int i=0;i<15;i++)H[i]=-1;
  14. for(int i=0;i<S;i++)
  15. {
  16. int x=L[i];
  17. cout<<"\nNow:"<<x;
  18. if(H[x]!=-1)continue;
  19. if(H[x-1]!=-1 && H[x+1]!=-1)
  20. {
  21. cout<<"\nBoth end-points available";
  22. int a=H[x-1];
  23. int b=H[x+1];
  24. H[a]=b;
  25. H[b]=a;
  26. H[x]=x;
  27. cout<<"\nH["<<x<<"]="<<H[x];
  28. }
  29. else if(H[x-1]!=-1)
  30. {
  31. cout<<"\nLeft available";
  32. H[H[x-1]]=x;
  33. H[x]=H[x-1];
  34. cout<<"\nH["<<x<<"]="<<H[x];
  35. }
  36. else if(H[x+1]!=-1)
  37. {
  38. cout<<"\nRight available";
  39. H[H[x+1]]=x;
  40. H[x]=H[x+1];
  41. cout<<"\nH["<<x<<"]="<<H[x];
  42. }
  43. else
  44. {
  45. cout<<"\nBoth end-points NOT available";
  46. H[x]=x;
  47. cout<<"\nH["<<x<<"]="<<H[x];
  48. }
  49. }
  50. int res=0;
  51. int l,h;
  52. for(int i=0;i<S;i++)
  53. {
  54. int x=L[i];
  55. if(res<(H[x]-x+1))
  56. {
  57. res=H[x]-x+1;
  58. l=min(x,H[x]);
  59. h=max(x,H[x]);
  60. }
  61. }
  62. cout<<"\nLength of maximum interval is "<<res<<" and it starts from "<<l<<" and ends at "<<h;
  63. return 0;
  64. }
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
Now:1
Both end-points NOT available
H[1]=1
Now:3
Both end-points NOT available
H[3]=3
Now:5
Both end-points NOT available
H[5]=5
Now:7
Both end-points NOT available
H[7]=7
Now:4
Both end-points available
H[4]=4
Now:6
Both end-points available
H[6]=6
Now:10
Both end-points NOT available
H[10]=10
Length of maximum interval is 5 and it starts from 3 and ends at 7