n개의 개별 요소로 구성된 배열이 주어졌습니다. 배열에 있는 최소 두 숫자의 곱의 최대값과 위치의 절대 차이를 찾습니다. 즉, i와 j가 0에서 n-1까지 변하는 경우 abs(i - j) * min(arr[i] arr[j])의 최대값을 찾습니다.
C 코드 문자열 배열
예:
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 최대값 찾기 시도해 보세요! 에이 간단한 해결책 이 문제는 각 요소를 하나씩 가져와 이 요소를 오른쪽에 있는 요소와 비교하는 것입니다. 그런 다음 최소값과 지수 간의 절대 차이의 곱을 계산하고 결과를 최대화합니다. 이 접근 방식의 시간 복잡도는 O(n^2)입니다.
안 효율적인 솔루션 선형 시간 복잡도 문제를 해결합니다. 우리는 두 개의 반복자를 사용합니다 왼쪽=0 그리고 오른쪽=n-1 arr[Left] 및 arr[right] 요소를 비교합니다.
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)
아래는 위의 아이디어를 구현한 것입니다.
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(arrn); 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(arrn): # 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(arrn)) # 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>
산출
16
시간 복잡도 : O(N log N) 여기서 N은 배열의 길이입니다.
공간 복잡도 : O(1) 추가 공간을 사용하지 않기 때문입니다.
어떻게 작동하나요?
위의 선형 알고리즘에서 잠재적인 쌍을 놓치지 않는다는 것을 보여주는 중요한 점, 즉 왼쪽++ 또는 오른쪽을 수행한다고 해서 maxProduct의 더 높은 값을 얻을 수 있는 경우가 발생하지 않는다는 것을 보여야 합니다.
우리는 항상 (오른쪽 - 왼쪽)을 곱한다는 점에 유의하세요.
- 도착[왼쪽]인 경우< arr[right] then smaller values of 오른쪽 현재 왼쪽의 경우 maxProduct의 더 높은 값을 생성할 수 없으므로 쓸모가 없습니다(arr[left]와 (right - left)를 곱하기 때문). arr[left]가 왼쪽에 있는 요소보다 크다면 어떻게 될까요? 이 경우 해당 요소에 대한 더 나은 쌍이 현재 권한으로 발견되어야 합니다. 그러므로 우리는 현재 왼쪽과 더 나은 쌍을 놓치지 않고 안전하게 왼쪽을 증가시킬 수 있습니다.
- arr[right]인 경우에도 비슷한 주장을 적용할 수 있습니다.< arr[left].