Encontre o valor máximo de abs(i - j) * min(arr[i], arr[j]) em uma matriz arr[]

Dado um array de n elementos distintos. Encontre o máximo do produto do mínimo de dois números na matriz e a diferença absoluta de suas posições, ou seja, encontre o valor máximo de abs(i - j) * min(arr[i] arr[j]) onde i e j variam de 0 a n-1. 

Exemplos:  

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 Encontre o valor máximo Experimente!

UM solução simples para este problema é pegar cada elemento um por um e comparar esse elemento com os elementos à direita dele. Em seguida, calcule o produto do mínimo deles e a diferença absoluta entre seus índices e maximize o resultado. A complexidade de tempo para esta abordagem é O(n^2).

Um solução eficiente para resolver o problema na complexidade do tempo linear. Pegamos dois iteradores Esquerda=0 e Direita=n-1 compare os elementos arr[Esquerda] e arr[direita].  

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) 

Abaixo está a implementação da ideia acima. 

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>   

Saída
16 

Complexidade de tempo: O (N log N) aqui N é o comprimento da matriz.

Complexidade Espacial: O (1) já que nenhum espaço extra é usado.

Como é que isso funciona?  
O importante é mostrar que não perdemos nenhum par potencial no algoritmo linear acima, ou seja, precisamos mostrar que fazer left++ ou right - não leva a um caso em que teríamos um valor mais alto de maxProduct.

Observe que sempre multiplicamos por (direita - esquerda). 

  1. Se arr[esquerda] < arr[right] then smaller values of certo para a esquerda atual são inúteis, pois não podem produzir um valor maior de maxProduct (porque multiplicamos com arr[esquerda] por (direita - esquerda)). E se arr[left] fosse maior que qualquer um dos elementos do lado esquerdo. Nesse caso, um par melhor para aquele elemento deve ter sido encontrado com a direita atual. Portanto, podemos aumentar com segurança para a esquerda sem perder nenhum par melhor com a esquerda atual.
  2. Argumentos semelhantes são aplicáveis ​​quando arr[right] < arr[left].