Finden Sie heraus, ob ein Subarray die Form eines Berges hat oder nicht

Finden Sie heraus, ob ein Subarray die Form eines Berges hat oder nicht
Probieren Sie es bei GfG Practice aus #practiceLinkDiv { display: none !important; }

Wir erhalten ein Array von Ganzzahlen und einen Bereich, den wir benötigen, um herauszufinden, ob das Subarray, das in diesen Bereich fällt, Werte in Form eines Berges hat oder nicht. Alle Werte des Subarrays haben die Form eines Berges, wenn entweder alle Werte steigen oder fallen oder zuerst steigen und dann fallen. 
Formaler ein Subarray [a1 a2 a3…aN] Man sagt, dass es die Form eines Berges hat, wenn es eine ganze Zahl K 1 gibt <= K <= N such that 
a1 <= a2 <= a3 .. <= aK >= a(K+1) >= a(K+2) …. >= aN  

Beispiele:  

  Input : Arr[]   = [2 3 2 4 4 6 3 2] Range = [0 2]   Output :    Yes   Explanation:   The output is yes  subarray is [2 3 2] so subarray first increases and then decreases   Input:    Arr[] = [2 3 2 4 4 6 3 2] Range = [2 7]   Output:   Yes   Explanation:   The output is yes  subarray is [2 4 4 6 3 2] so subarray first increases and then decreases   Input:   Arr[]= [2 3 2 4 4 6 3 2] Range = [1 3]   Output:   no   Explanation:   The output is no subarray is [3 2 4] so subarray is not in the form above stated 
Recommended Practice Berg-Subarray-Problem Probieren Sie es aus!

Lösung:  

    Ansatz: Das Problem hat mehrere Abfragen, daher sollte für jede Abfrage die Lösung mit möglichst geringem Zeitaufwand berechnet werden. Erstellen Sie also zwei zusätzliche Leerzeichen in der Länge des ursprünglichen Arrays. Suchen Sie für jedes Element den letzten Index auf der linken Seite, der ansteigend ist, d. h. größer als sein vorheriges Element, und finden Sie das Element auf der rechten Seite, um den ersten Index auf der rechten Seite zu speichern, der absteigend ist, d. h. größer als sein nächstes Element. Wenn diese Werte für jeden Index in konstanter Zeit berechnet werden können, kann die Antwort für jeden gegebenen Bereich in konstanter Zeit angegeben werden. Algorithmus:  
    1. Erstellen Sie zwei zusätzliche Längenräume N links Und Rechts und eine zusätzliche Variable lastptr
    2. Initialisieren links[0] = 0 und lastptr = 0
    3. Durchlaufen Sie das ursprüngliche Array vom zweiten Index bis zum Ende
    4. Überprüfen Sie für jeden Index, ob er größer als das vorherige Element ist. Wenn ja, aktualisieren Sie ihn lastptr mit dem aktuellen Index.
    5. Für jeden Indexspeicher die lastptr In links[i]
    6. initialisieren rechts[N-1] = N-1 und lastptr = N-1
    7. Durchlaufen Sie das ursprüngliche Array vom vorletzten Index bis zum Anfang
    8. Überprüfen Sie bei jedem Index, ob er größer als das nächste Element ist. Wenn ja, aktualisieren Sie ihn lastptr mit dem aktuellen Index.
    9. Für jeden Indexspeicher die lastptr In richtig[i]
    10. Bearbeiten Sie nun die Abfragen
    11. für jede Anfrage lr Wenn rechts[l] >= links[r] dann drucken Ja anders NEIN
    Durchführung:
C++
   // C++ program to check whether a subarray is in   // mountain form or not   #include          using     namespace     std  ;   // Utility method to construct left and right array   int     preprocess  (  int     arr  []     int     N       int     left  []     int     right  [])   {      // Initialize first left index as that index only      left  [  0  ]     =     0  ;      int     lastIncr     =     0  ;      for     (  int     i     =     1  ;     i      <     N  ;     i  ++  )      {      // if current value is greater than previous      // update last increasing      if     (  arr  [  i  ]     >     arr  [  i     -     1  ])      lastIncr     =     i  ;      left  [  i  ]     =     lastIncr  ;      }      // Initialize last right index as that index only      right  [  N     -     1  ]     =     N     -     1  ;      int     firstDecr     =     N     -     1  ;      for     (  int     i     =     N     -     2  ;     i     >=     0  ;     i  --  )      {      // if current value is greater than next      // update first decreasing      if     (  arr  [  i  ]     >     arr  [  i     +     1  ])      firstDecr     =     i  ;      right  [  i  ]     =     firstDecr  ;      }   }   // Method returns true if arr[L..R] is in mountain form   bool     isSubarrayMountainForm  (  int     arr  []     int     left  []      int     right  []     int     L       int     R  )   {      // return true only if right at starting range is      // greater than left at ending range      return     (  right  [  L  ]     >=     left  [  R  ]);   }   // Driver code to test above methods   int     main  ()   {      int     arr  []     =     {  2       3       2       4       4       6       3       2  };      int     N     =     sizeof  (  arr  )     /     sizeof  (  int  );      int     left  [  N  ]     right  [  N  ];      preprocess  (  arr       N       left       right  );      int     L     =     0  ;      int     R     =     2  ;      if     (  isSubarrayMountainForm  (  arr       left       right       L       R  ))      cout      < <     'Subarray is in mountain form  n  '  ;      else      cout      < <     'Subarray is not in mountain form  n  '  ;      L     =     1  ;      R     =     3  ;      if     (  isSubarrayMountainForm  (  arr       left       right       L       R  ))      cout      < <     'Subarray is in mountain form  n  '  ;      else      cout      < <     'Subarray is not in mountain form  n  '  ;      return     0  ;   }   
Java
   // Java program to check whether a subarray is in   // mountain form or not   class   SubArray   {      // Utility method to construct left and right array      static     void     preprocess  (  int     arr  []       int     N       int     left  []       int     right  []  )      {      // initialize first left index as that index only      left  [  0  ]     =     0  ;      int     lastIncr     =     0  ;          for     (  int     i     =     1  ;     i      <     N  ;     i  ++  )      {      // if current value is greater than previous      // update last increasing      if     (  arr  [  i  ]     >     arr  [  i     -     1  ]  )      lastIncr     =     i  ;      left  [  i  ]     =     lastIncr  ;      }          // initialize last right index as that index only      right  [  N     -     1  ]     =     N     -     1  ;      int     firstDecr     =     N     -     1  ;          for     (  int     i     =     N     -     2  ;     i     >=     0  ;     i  --  )      {      // if current value is greater than next      // update first decreasing      if     (  arr  [  i  ]     >     arr  [  i     +     1  ]  )      firstDecr     =     i  ;      right  [  i  ]     =     firstDecr  ;      }      }          // method returns true if arr[L..R] is in mountain form      static     boolean     isSubarrayMountainForm  (  int     arr  []       int     left  []        int     right  []       int     L       int     R  )      {      // return true only if right at starting range is      // greater than left at ending range      return     (  right  [  L  ]     >=     left  [  R  ]  );      }          public     static     void     main  (  String  []     args  )      {      int     arr  []     =     {  2       3       2       4       4       6       3       2  };      int     N     =     arr  .  length  ;      int     left  []     =     new     int  [  N  ]  ;      int     right  []     =     new     int  [  N  ]  ;      preprocess  (  arr       N       left       right  );      int     L     =     0  ;      int     R     =     2  ;          if     (  isSubarrayMountainForm  (  arr       left       right       L       R  ))      System  .  out  .  println  (  'Subarray is in mountain form'  );      else      System  .  out  .  println  (  'Subarray is not in mountain form'  );          L     =     1  ;      R     =     3  ;          if     (  isSubarrayMountainForm  (  arr       left       right       L       R  ))      System  .  out  .  println  (  'Subarray is in mountain form'  );      else      System  .  out  .  println  (  'Subarray is not in mountain form'  );      }   }   // This Code is Contributed by Saket Kumar   
Python3
   # Python 3 program to check whether a subarray is in   # mountain form or not   # Utility method to construct left and right array   def   preprocess  (  arr     N     left     right  ):   # initialize first left index as that index only   left  [  0  ]   =   0   lastIncr   =   0   for   i   in   range  (  1    N  ):   # if current value is greater than previous   # update last increasing   if   (  arr  [  i  ]   >   arr  [  i   -   1  ]):   lastIncr   =   i   left  [  i  ]   =   lastIncr   # initialize last right index as that index only   right  [  N   -   1  ]   =   N   -   1   firstDecr   =   N   -   1   i   =   N   -   2   while  (  i   >=   0  ):   # if current value is greater than next   # update first decreasing   if   (  arr  [  i  ]   >   arr  [  i   +   1  ]):   firstDecr   =   i   right  [  i  ]   =   firstDecr   i   -=   1   # method returns true if arr[L..R] is in mountain form   def   isSubarrayMountainForm  (  arr     left     right     L     R  ):   # return true only if right at starting range is   # greater than left at ending range   return   (  right  [  L  ]   >=   left  [  R  ])   # Driver code    if   __name__   ==   '__main__'  :   arr   =   [  2     3     2     4     4     6     3     2  ]   N   =   len  (  arr  )   left   =   [  0   for   i   in   range  (  N  )]   right   =   [  0   for   i   in   range  (  N  )]   preprocess  (  arr     N     left     right  )   L   =   0   R   =   2   if   (  isSubarrayMountainForm  (  arr     left     right     L     R  )):   print  (  'Subarray is in mountain form'  )   else  :   print  (  'Subarray is not in mountain form'  )   L   =   1   R   =   3   if   (  isSubarrayMountainForm  (  arr     left     right     L     R  )):   print  (  'Subarray is in mountain form'  )   else  :   print  (  'Subarray is not in mountain form'  )   # This code is contributed by   # Surendra_Gangwar   
C#
   // C# program to check whether    // a subarray is in mountain    // form or not   using     System  ;   class     GFG   {          // Utility method to construct       // left and right array      static     void     preprocess  (  int     []  arr       int     N           int     []  left       int     []  right  )      {      // initialize first left       // index as that index only      left  [  0  ]     =     0  ;      int     lastIncr     =     0  ;          for     (  int     i     =     1  ;     i      <     N  ;     i  ++  )      {      // if current value is       // greater than previous      // update last increasing      if     (  arr  [  i  ]     >     arr  [  i     -     1  ])      lastIncr     =     i  ;      left  [  i  ]     =     lastIncr  ;      }          // initialize last right       // index as that index only      right  [  N     -     1  ]     =     N     -     1  ;      int     firstDecr     =     N     -     1  ;          for     (  int     i     =     N     -     2  ;     i     >=     0  ;     i  --  )      {      // if current value is       // greater than next      // update first decreasing      if     (  arr  [  i  ]     >     arr  [  i     +     1  ])      firstDecr     =     i  ;      right  [  i  ]     =     firstDecr  ;      }      }          // method returns true if      // arr[L..R] is in mountain form      static     bool     isSubarrayMountainForm  (  int     []  arr       int     []  left        int     []  right       int     L       int     R  )      {      // return true only if right at       // starting range is greater       // than left at ending range      return     (  right  [  L  ]     >=     left  [  R  ]);      }              // Driver Code      static     public     void     Main     ()      {      int     []  arr     =     {  2       3       2       4        4       6       3       2  };      int     N     =     arr  .  Length  ;      int     []  left     =     new     int  [  N  ];      int     []  right     =     new     int  [  N  ];      preprocess  (  arr       N       left       right  );          int     L     =     0  ;      int     R     =     2  ;          if     (  isSubarrayMountainForm  (  arr       left           right       L       R  ))      Console  .  WriteLine  (  'Subarray is in '     +         'mountain form'  );      else      Console  .  WriteLine  (  'Subarray is not '     +         'in mountain form'  );          L     =     1  ;      R     =     3  ;          if     (  isSubarrayMountainForm  (  arr       left           right       L       R  ))      Console  .  WriteLine  (  'Subarray is in '     +         'mountain form'  );      else      Console  .  WriteLine  (  'Subarray is not '     +         'in mountain form'  );      }   }   // This code is contributed by aj_36   
JavaScript
    <  script  >      // Javascript program to check whether       // a subarray is in mountain       // form or not          // Utility method to construct       // left and right array      function     preprocess  (  arr       N       left       right  )      {      // initialize first left       // index as that index only      left  [  0  ]     =     0  ;      let     lastIncr     =     0  ;          for     (  let     i     =     1  ;     i      <     N  ;     i  ++  )      {      // if current value is       // greater than previous      // update last increasing      if     (  arr  [  i  ]     >     arr  [  i     -     1  ])      lastIncr     =     i  ;      left  [  i  ]     =     lastIncr  ;      }          // initialize last right       // index as that index only      right  [  N     -     1  ]     =     N     -     1  ;      let     firstDecr     =     N     -     1  ;          for     (  let     i     =     N     -     2  ;     i     >=     0  ;     i  --  )      {      // if current value is       // greater than next      // update first decreasing      if     (  arr  [  i  ]     >     arr  [  i     +     1  ])      firstDecr     =     i  ;      right  [  i  ]     =     firstDecr  ;      }      }          // method returns true if      // arr[L..R] is in mountain form      function     isSubarrayMountainForm  (  arr       left       right       L       R  )      {      // return true only if right at       // starting range is greater       // than left at ending range      return     (  right  [  L  ]     >=     left  [  R  ]);      }          let     arr     =     [  2       3       2       4       4       6       3       2  ];      let     N     =     arr  .  length  ;      let     left     =     new     Array  (  N  );      let     right     =     new     Array  (  N  );      preprocess  (  arr       N       left       right  );      let     L     =     0  ;      let     R     =     2  ;      if     (  isSubarrayMountainForm  (  arr       left       right       L       R  ))      document  .  write  (  'Subarray is in '     +     'mountain form'     +     ' 
'
); else document . write ( 'Subarray is not ' + 'in mountain form' + '
'
); L = 1 ; R = 3 ; if ( isSubarrayMountainForm ( arr left right L R )) document . write ( 'Subarray is in ' + 'mountain form' ); else document . write ( 'Subarray is not ' + 'in mountain form' ); < /script>
    Ausgabe:
Subarray is in mountain form Subarray is not in mountain form 
    Komplexitätsanalyse:  
      Zeitkomplexität: An). 
      Da nur zwei Durchläufe erforderlich sind, beträgt die Zeitkomplexität O(n). Raumkomplexität: An). 
      Es sind zwei zusätzliche Räume der Länge n erforderlich, sodass die Raumkomplexität O(n) beträgt.


 

Quiz erstellen