📌  相关文章
📜  所有Y大小子数组中最大和最小元素之间的最小差异

📅  最后修改于: 2021-05-08 16:50:55             🧑  作者: Mango

给定大小为N且整数Y的数组arr [] ,任务是在大小为Y的所有子数组中的最大元素和最小元素之间找到所有差值中的最小值。

例子:

天真的方法:天真的想法是遍历范围[0,N – Y]中的每个索引i,使用另一个循环从i个索引遍历到(i + Y – 1)索引,然后计算最小和最大元素在大小为Y的子数组中,因此计算第i次迭代的最大元素和最小元素之差。最后,通过检查差异,评估最小差异。

时间复杂度: O(N * Y)
辅助空间: O(1)

高效的方法:其想法是使用本手册中讨论的方法的概念 下一个更大元素文章步骤如下:

  1. 构建两个数组maxarr []minarr [] ,其中maxarr []将存储元素的索引,该索引比第i索引的元素大一个,而minarr []将存储下一个元素的索引,该索引小于该元素的索引在第i索引处
  2. 在上述两种情况下,都使用0初始化堆栈以存储索引。
  3. 对于每个索引, i在[0,N – Y]范围内,使用嵌套循环和滑动窗口方法形成submaxsubmin两个数组。这些数组将在第i次迭代中将最大和最小元素存储在子数组中。
  4. 最后,计算最小差异。

下面是上述方法的实现:

C++
// C++ program for the above approach 
#include  
using namespace std; 
  
// Function to get the maximum of all 
// the subarrays of size Y 
vector get_submaxarr(int* arr, 
                        int n, int y) 
{ 
    int j = 0; 
    stack stk; 
  
    // ith index of maxarr array 
    // will be the index upto which 
    // Arr[i] is maximum 
    vector maxarr(n); 
    stk.push(0); 
  
    for (int i = 1; i < n; i++) { 
  
        // Stack is used to find the 
        // next larger element and 
        // keeps track of index of 
        // current iteration 
        while (stk.empty() == false
            and arr[i] > arr[stk.top()]) { 
  
            maxarr[stk.top()] = i - 1; 
            stk.pop(); 
        } 
        stk.push(i); 
    } 
  
    // Loop for remaining indexes 
    while (!stk.empty()) { 
  
        maxarr[stk.top()] = n - 1; 
        stk.pop(); 
    } 
    vector submax; 
  
    for (int i = 0; i <= n - y; i++) { 
  
        // j < i used to keep track 
        // whether jth element is 
        // inside or outside the window 
        while (maxarr[j] < i + y - 1 
            or j < i) { 
            j++; 
        } 
  
        submax.push_back(arr[j]); 
    } 
  
    // Return submax 
    return submax; 
} 
  
// Function to get the minimum for 
// all subarrays of size Y 
vector get_subminarr(int* arr, 
                        int n, int y) 
{ 
    int j = 0; 
  
    stack stk; 
  
    // ith index of minarr array 
    // will be the index upto which 
    // Arr[i] is minimum 
    vector minarr(n); 
    stk.push(0); 
  
    for (int i = 1; i < n; i++) { 
  
        // Stack is used to find the 
        // next smaller element and 
        // keeping track of index of 
        // current iteration 
        while (stk.empty() == false
            and arr[i] < arr[stk.top()]) { 
  
            minarr[stk.top()] = i; 
            stk.pop(); 
        } 
        stk.push(i); 
    } 
  
    // Loop for remaining indexes 
    while (!stk.empty()) { 
  
        minarr[stk.top()] = n; 
        stk.pop(); 
    } 
  
    vector submin; 
  
    for (int i = 0; i <= n - y; i++) { 
  
        // j < i used to keep track 
        // whether jth element is inside 
        // or outside the window 
  
        while (minarr[j] <= i + y - 1 
            or j < i) { 
            j++; 
        } 
  
        submin.push_back(arr[j]); 
    } 
  
    // Return submin 
    return submin; 
} 
  
// Function to get minimum difference 
void getMinDifference(int Arr[], int N, 
                    int Y) 
{ 
    // Create submin and submax arrays 
    vector submin 
        = get_subminarr(Arr, N, Y); 
  
    vector submax 
        = get_submaxarr(Arr, N, Y); 
  
    // Store initial difference 
    int minn = submax[0] - submin[0]; 
    int b = submax.size(); 
  
    for (int i = 1; i < b; i++) { 
  
        // Calculate temporary difference 
        int dif = submax[i] - submin[i]; 
        minn = min(minn, dif); 
    } 
  
    // Final minimum difference 
    cout << minn << "\n"; 
} 
  
// Driver Code 
int main() 
{ 
    // Given array arr[] 
    int arr[] = { 1, 2, 3, 3, 2, 2 }; 
    int N = sizeof arr / sizeof arr[0]; 
  
    // Given subarray size 
    int Y = 4; 
  
    // Function Call 
    getMinDifference(arr, N, Y); 
    return 0; 
}


Python3
# Python3 program for the above approach 
  
# Function to get the maximum of all 
# the subarrays of size Y 
def get_submaxarr(arr, n, y): 
      
    j = 0
    stk = []
      
    # ith index of maxarr array 
    # will be the index upto which 
    # Arr[i] is maximum 
    maxarr = [0] * n 
    stk.append(0) 
  
    for i in range(1, n):
  
        # Stack is used to find the 
        # next larger element and 
        # keeps track of index of 
        # current iteration 
        while (len(stk) > 0 and 
                 arr[i] > arr[stk[-1]]):
            maxarr[stk[-1]] = i - 1
            stk.pop() 
              
        stk.append(i)
  
    # Loop for remaining indexes 
    while (stk):
        maxarr[stk[-1]] = n - 1
        stk.pop()
          
    submax = [] 
      
    for i in range(n - y + 1):
  
        # j < i used to keep track 
        # whether jth element is 
        # inside or outside the window 
        while (maxarr[j] < i + y - 1 or
                       j < i):
            j += 1
              
        submax.append(arr[j])
  
    # Return submax 
    return submax
  
# Function to get the minimum for 
# all subarrays of size Y 
def get_subminarr(arr, n, y):
      
    j = 0
    stk = [] 
      
    # ith index of minarr array 
    # will be the index upto which 
    # Arr[i] is minimum 
    minarr = [0] * n
    stk.append(0)
      
    for i in range(1 , n):
          
        # Stack is used to find the 
        # next smaller element and 
        # keeping track of index of 
        # current iteration 
        while (stk and arr[i] < arr[stk[-1]]):
            minarr[stk[-1]] = i
            stk.pop() 
              
        stk.append(i) 
          
    # Loop for remaining indexes 
    while (stk):
        minarr[stk[-1]] = n
        stk.pop()
          
    submin = []
      
    for i in range(n - y + 1):
          
        # j < i used to keep track 
        # whether jth element is inside 
        # or outside the window 
        while (minarr[j] <= i + y - 1 or
                      j < i):
            j += 1
              
        submin.append(arr[j])
          
    # Return submin 
    return submin 
  
# Function to get minimum difference 
def getMinDifference(Arr, N, Y):
      
    # Create submin and submax arrays
    submin = get_subminarr(Arr, N, Y)
    submax = get_submaxarr(Arr, N, Y)
      
    # Store initial difference 
    minn = submax[0] - submin[0]
    b = len(submax)
      
    for i in range(1, b):
          
        # Calculate temporary difference 
        diff = submax[i] - submin[i]
        minn = min(minn, diff)
      
    # Final minimum difference 
    print(minn)
      
# Driver code
  
# Given array arr[]
arr = [ 1, 2, 3, 3, 2, 2 ]
N = len(arr)
  
# Given subarray size
Y = 4
  
# Function call
getMinDifference(arr, N, Y)
      
# This code is contributed by Stuti Pathak


输出:
1

时间复杂度: O(N)
辅助空间: O(N)