Zoek de maximale waarde van abs(i - j) * min(arr[i], arr[j]) in een array arr[]

Gegeven een array van n verschillende elementen. Vind het maximum van het product van minimaal twee getallen in de array en het absolute verschil van hun posities, d.w.z. vind de maximale waarde van abs(i - j) * min(arr[i] arr[j]) waarbij i en j variëren van 0 tot n-1. 

Voorbeelden:  

Input : arr[] = {3 2 1 4} Output: 9 // arr[0] = 3 and arr[3] = 4 minimum of them is 3 and // absolute difference between their position is // abs(0-3) = 3. So product is 3*3 = 9 Input : arr[] = {8 1 9 4} Output: 16 // arr[0] = 8 and arr[2] = 9 minimum of them is 8 and // absolute difference between their position is // abs(0-2) = 2. So product is 8*2 = 16  
Recommended Practice Zoek maximale waarde Probeer het!

A eenvoudige oplossing want dit probleem is om elk element één voor één te nemen en dit element te vergelijken met de elementen rechts ervan. Bereken vervolgens het product van het minimum ervan en het absolute verschil tussen hun indexen en maximaliseer het resultaat. De tijdscomplexiteit voor deze benadering is O(n^2).

Een efficiënte oplossing om het probleem in lineaire tijdscomplexiteit op te lossen. We nemen twee iteratoren Links=0 En Rechts=n-1 vergelijk de elementen arr[Links] en arr[rechts].  

left = 0 right = n-1 maxProduct = -INF While (left  < right) If arr[Left]  < arr[right] currProduct = arr[Left]*(right-Left) Left++ . If arr[right]  < arr[Left] currProduct = arr[Right]*(Right-Left) Right-- . maxProduct = max(maxProduct currProduct) 

Hieronder ziet u de implementatie van bovenstaand idee. 

C++
   // C++ implementation of code   #include       using     namespace     std  ;   // Function to calculate maximum value of    // abs(i - j) * min(arr[i] arr[j]) in arr[]   int     Maximum_Product  (  int     arr  []     int     n  )   {      int     maxProduct     =     INT_MIN  ;     // Initialize result      int     currProduct  ;     // product of current pair      // loop until they meet with each other      int     Left     =     0       right     =     n  -1  ;      while     (  Left      <     right  )      {      if     (  arr  [  Left  ]      <     arr  [  right  ])      {      currProduct     =     arr  [  Left  ]  *  (  right  -  Left  );      Left  ++  ;      }      else     // arr[right] is smaller      {      currProduct     =     arr  [  right  ]  *  (  right  -  Left  );      right  --  ;      }      // maximizing the product      maxProduct     =     max  (  maxProduct       currProduct  );      }      return     maxProduct  ;   }   // Driver program to test the case   int     main  ()   {      int     arr  []     =     {  8       1       9       4  };      int     n     =     sizeof  (  arr  )  /  sizeof  (  arr  [  0  ]);      cout      < <     Maximum_Product  (  arr    n  );      return     0  ;   }   
Java
   // Java implementation of code   import     java.util.*  ;   class   GFG     {          // Function to calculate maximum value of      // abs(i - j) * min(arr[i] arr[j]) in arr[]      static     int     Maximum_Product  (  int     arr  []       int     n  )     {          // Initialize result      int     maxProduct     =     Integer  .  MIN_VALUE  ;             // product of current pair      int     currProduct  ;         // loop until they meet with each other      int     Left     =     0       right     =     n     -     1  ;      while     (  Left      <     right  )     {      if     (  arr  [  Left  ]      <     arr  [  right  ]  )     {      currProduct     =     arr  [  Left  ]     *     (  right     -     Left  );      Left  ++  ;      }             // arr[right] is smaller      else         {      currProduct     =     arr  [  right  ]     *     (  right     -     Left  );      right  --  ;      }      // maximizing the product      maxProduct     =     Math  .  max  (  maxProduct       currProduct  );      }      return     maxProduct  ;   }   // Driver code   public     static     void     main  (  String  []     args  )      {      int     arr  []     =     {  8       1       9       4  };      int     n     =     arr  .  length  ;      System  .  out  .  print  (  Maximum_Product  (  arr       n  ));   }   }   // This code is contributed by Anant Agarwal.   
Python3
   # Python implementation of code   # Function to calculate   # maximum value of    # abs(i - j) * min(arr[i]   # arr[j]) in arr[]   def   Maximum_Product  (  arr    n  ):   # Initialize result   maxProduct   =   -  2147483648   # product of current pair   currProduct  =  0   # loop until they meet with each other   Left   =   0   right   =   n  -  1   while   (  Left    <   right  ):   if   (  arr  [  Left  ]    <   arr  [  right  ]):   currProduct   =   arr  [  Left  ]  *  (  right  -  Left  )   Left  +=  1   else  :   # arr[right] is smaller   currProduct   =   arr  [  right  ]  *  (  right  -  Left  )   right  -=  1   # maximizing the product   maxProduct   =   max  (  maxProduct     currProduct  )   return   maxProduct   # Driver code   arr   =   [  8     1     9     4  ]   n   =   len  (  arr  )   print  (  Maximum_Product  (  arr    n  ))   # This code is contributed   # by Anant Agarwal.   
C#
   // C# implementation of code   using     System  ;   class     GFG     {       // Function to calculate maximum   // value of abs(i - j) * min(arr[i]   // arr[j]) in arr[]   static     int     Maximum_Product  (  int     []  arr        int     n  )   {          // Initialize result      int     maxProduct     =     int  .  MinValue  ;             // product of current pair      int     currProduct  ;         // loop until they meet       // with each other      int     Left     =     0       right     =     n     -     1  ;      while     (  Left      <     right  )     {      if     (  arr  [  Left  ]      <     arr  [  right  ])      {      currProduct     =     arr  [  Left  ]     *         (  right     -     Left  );      Left  ++  ;      }             // arr[right] is smaller      else      {      currProduct     =     arr  [  right  ]     *      (  right     -     Left  );      right  --  ;      }      // maximizing the product      maxProduct     =     Math  .  Max  (  maxProduct           currProduct  );      }      return     maxProduct  ;   }   // Driver code   public     static     void     Main  ()      {      int     []  arr     =     {  8       1       9       4  };      int     n     =     arr  .  Length  ;      Console  .  Write  (  Maximum_Product  (  arr       n  ));   }   }   // This code is contributed by nitin mittal.   
PHP
      // PHP implementation of code   // Function to calculate    // maximum value of    // abs(i - j) * min(arr[i]    // arr[j]) in arr[]   function   Maximum_Product  (  $arr     $n  )   {   $INT_MIN   =   0  ;   // Initialize result   $maxProduct   =   $INT_MIN  ;   // product of current pair   $currProduct  ;   // loop until they meet   // with each other   $Left   =   0  ;   $right   =   $n   -   1  ;   while   (  $Left    <   $right  )   {   if   (  $arr  [  $Left  ]    <   $arr  [  $right  ])   {   $currProduct   =   $arr  [  $Left  ]   *   (  $right   -   $Left  );   $Left  ++  ;   }   // arr[right] is smaller   else   {   $currProduct   =   $arr  [  $right  ]   *   (  $right   -   $Left  );   $right  --  ;   }   // maximizing the product   $maxProduct   =   max  (  $maxProduct     $currProduct  );   }   return   $maxProduct  ;   }   // Driver Code   $arr   =   array  (  8     1     9     4  );   $n   =   sizeof  (  $arr  )   /   sizeof  (  $arr  [  0  ]);   echo   Maximum_Product  (  $arr     $n  );   // This code is contributed   // by nitin mittal.    ?>   
JavaScript
    <  script  >   // Javascript implementation of code   // Function to calculate   // maximum value of   // abs(i - j) * min(arr[i]   // arr[j]) in arr[]   function     Maximum_Product  (  arr       n  )   {      let     INT_MIN     =     0  ;      // Initialize result      let     maxProduct     =     INT_MIN  ;      // Product of current pair      let     currProduct  ;      // Loop until they meet      // with each other      let     Left     =     0       right     =     n     -     1  ;      while     (  Left      <     right  )         {      if     (  arr  [  Left  ]      <     arr  [  right  ])      {      currProduct     =     arr  [  Left  ]     *      (  right     -     Left  );      Left  ++  ;      }      // arr[right] is smaller      else         {      currProduct     =     arr  [  right  ]     *      (  right     -     Left  );      right  --  ;      }      // Maximizing the product      maxProduct     =     Math  .  max  (  maxProduct        currProduct  );      }      return     maxProduct  ;   }   // Driver Code   let     arr     =     new     Array  (  8       1       9       4  );   let     n     =     arr  .  length  ;   document  .  write  (  Maximum_Product  (  arr       n  ));   // This code is contributed by Saurabh Jaiswal    <  /script>   

Uitvoer
16 

Tijdcomplexiteit: O(N log N) hier is N de lengte van de array.

Ruimtecomplexiteit: O(1) omdat er geen extra ruimte wordt gebruikt.

Hoe werkt dit?  
Het belangrijkste om te laten zien dat we geen enkel potentieel paar missen in het bovenstaande lineaire algoritme, dat wil zeggen dat we moeten laten zien dat links++ of rechts doen niet leidt tot een geval waarin we een hogere waarde van maxProduct zouden hebben gekregen.

Houd er rekening mee dat we altijd vermenigvuldigen met (rechts - links). 

  1. Als arr[links] < arr[right] then smaller values of rechts voor huidig ​​links zijn nutteloos omdat ze geen hogere waarde van maxProduct kunnen produceren (omdat we vermenigvuldigen met arr[links] met (rechts - links)). Wat als arr[left] groter was dan elk van de elementen aan de linkerkant. In dat geval moet er met het huidige recht een beter paar voor dat element gevonden zijn. Daarom kunnen we links veilig vergroten zonder een beter paar met het huidige links te missen.
  2. Soortgelijke argumenten zijn van toepassing wanneer arr[right] < arr[left].