📌  相关文章
📜  计算子数组中最小的每个子数组|套装2

📅  最后修改于: 2021-05-17 05:14:55             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,任务是创建一个大小为N的数组brr [] ,其中brr [i]代表其中arr [i]是最小元素的子数组的数量。

例子:

散列方法:遍历数组以找到所有可能的子数组的最小元素,并将其计数存储在Map中。请按照以下步骤解决问题:

  1. 创建一个Map来存储每个元素的子数组计数。
  2. 遍历所有可能的子数组,找到子数组中的最小元素。
  3. Map中获得的最小元素的增量计数
  4. 最后,为每个数组元素打印在Map中获得的频率。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate total number
// of sub-arrays for each element
// where that element is occurring
// as the minimum element
void minSubarray(int* arr, int N)
{
 
    // Map for storing the number of
    // sub-arrays for each element
    unordered_map m;
 
    // Traverse over all possible subarrays
    for (int i = 0; i < N; i++) {
 
        int mini = INT_MAX;
 
        for (int j = i; j < N; j++) {
 
            // Minimum in each subarray
            mini = min(mini, arr[j]);
            m[mini]++;
        }
    }
 
    // Print the result
    for (int i = 0; i < N; i++) {
 
        cout << m[arr[i]] << " ";
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { 3, 2, 1, 4 };
    int N = sizeof(arr) / sizeof(int);
 
    // Function Call
    minSubarray(arr, N);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
 
// Function to calculate total
// number of sub-arrays for each
// element where that element is
// occurring as the minimum element
static void minSubarray(int []arr,
                        int N)
{
  // Map for storing the number of
  // sub-arrays for each element
  HashMap mp = new HashMap();
 
  // Traverse over all possible
  // subarrays
  for (int i = 0; i < N; i++)
  {
    int mini = Integer.MAX_VALUE;
 
    for (int j = i; j < N; j++)
    {
      // Minimum in each subarray
      mini = Math.min(mini, arr[j]);
      if(mp.containsKey(mini))
      {
        mp.put(mini, mp.get(mini) + 1);
      }
      else
      {
        mp.put(mini, 1);
      }
    }
  }
 
  // Print the result
  for (int i = 0; i < N; i++)
  {
    System.out.print(mp.get(arr[i]) + " ");
  }
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {3, 2, 1, 4};
  int N = arr.length;
 
  // Function Call
  minSubarray(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for
# the above approach
 
# Function to calculate total
# number of sub-arrays for
# each element where that
# element is occurring as the
# minimum element
def minSubarray(arr, N):
 
    # Map for storing the
    # number of sub-arrays
    # for each element
    m = {}
 
    # Traverse over all
    # possible subarrays
    for i in range(N):
 
        mini = 10 ** 9
 
        for j in range(i, N):
 
            # Minimum in each subarray
            mini = min(mini, arr[j])
            m[mini] = m.get(mini, 0) + 1
 
    # Print result
    for i in arr:
        print(m[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
 
    arr = [3, 2, 1, 4]
    N = len(arr)
 
    # Function Call
    minSubarray(arr, N)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to calculate total
// number of sub-arrays for each
// element where that element is
// occurring as the minimum element
static void minSubarray(int []arr,
                        int N)
{
   
  // Map for storing the number of
  // sub-arrays for each element
  Dictionary mp = new Dictionary();
   
  // Traverse over all possible
  // subarrays
  for(int i = 0; i < N; i++)
  {
    int mini = int.MaxValue;
 
    for(int j = i; j < N; j++)
    {
       
      // Minimum in each subarray
      mini = Math.Min(mini, arr[j]);
       
      if (mp.ContainsKey(mini))
      {
        mp[mini] = mp[mini] + 1;
      }
      else
      {
        mp.Add(mini, 1);
      }
    }
  }
 
  // Print the result
  for(int i = 0; i < N; i++)
  {
    Console.Write(mp[arr[i]] + " ");
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = { 3, 2, 1, 4 };
  int N = arr.Length;
 
  // Function Call
  minSubarray(arr, N);
}
}
 
// This code is contributed by Amit Katiyar


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count subarrays
// for each element where it is
// the minimum
void minSubarray(int* arr, int N)
{
    int result[N];
    stack > l, r;
 
    // For the length of strictly larger
    // numbers on the left of A[i]
    for (int i = 0; i < N; i++) {
 
        int count = 1;
        while (!l.empty()
               && l.top().first > arr[i]) {
 
            count += l.top().second;
            l.pop();
        }
        l.push({ arr[i], count });
 
        // Storing x in result[i]
        result[i] = count;
    }
 
    // For the length of strictly larger
    // numbers on the right of A[i]
    for (int i = N - 1; i >= 0; i--) {
 
        int count = 1;
        while (!r.empty()
               && r.top().first >= arr[i]) {
 
            count += r.top().second;
            r.pop();
        }
        r.push({ arr[i], count });
 
        // Store x*y in result array
        result[i] *= count;
    }
 
    // Print the result
    for (int i = 0; i < N; i++) {
 
        cout << result[i] << " ";
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { 3, 2, 1, 4 };
    int N = sizeof(arr) / sizeof(int);
 
    // Function Call
    minSubarray(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
static class pair
{
    int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
 
// Function to count subarrays
// for each element where it is
// the minimum
static void minSubarray(int []arr, int N)
{
    int []result = new int[N];
    Stack l = new Stack<>();
    Stack r = new Stack<>();
 
    // For the length of strictly larger
    // numbers on the left of A[i]
    for(int i = 0; i < N; i++)
    {
        int count = 1;
        while (!l.isEmpty() &&
                l.peek().first > arr[i])
        {
            count += l.peek().second;
            l.pop();
        }
        l.add(new pair(arr[i], count));
 
        // Storing x in result[i]
        result[i] = count;
    }
 
    // For the length of strictly larger
    // numbers on the right of A[i]
    for(int i = N - 1; i >= 0; i--)
    {
        int count = 1;
        while (!r.isEmpty() &&
                r.peek().first >= arr[i])
        {
            count += r.peek().second;
            r.pop();
        }
        r.add(new pair(arr[i], count));
         
        // Store x*y in result array
        result[i] *= count;
    }
 
    // Print the result
    for(int i = 0; i < N; i++)
    {
        System.out.print(result[i] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 1, 4 };
    int N = arr.length;
 
    // Function Call
    minSubarray(arr, N);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the
# above approach
 
# Function to count subarrays
# for each element where it is
# the minimum
def minSubarray(arr, N):
   
    result = [0] * N
    l = []
    r = []
 
    # For the length of strictly
    # larger numbers on the left
    # of A[i]
    for i in range(N):
        count = 1;
        while (len(l) != 0 and
               l[-1][0] > arr[i]):
            count += l[-1][1]
            l.pop()
 
        l.append([arr[i], count])
 
        # Storing x in result[i]
        result[i] = count;
 
    # For the length of
    # strictly larger
    # numbers on the
    # right of A[i]
    for i in range(N - 1,
                   -1, -1):
        count = 1;
        while (len(r) != 0 and
               r[-1][0] >= arr[i]):
            count += r[-1][1]
            r.pop();
 
        r.append([arr[i], count]);
 
        # Store x*y in result
        # array
        result[i] *= count
 
    # Print the result
    for i in range(N):
        print(result[i],
              end = " ")
 
# Driver Code
if __name__ == "__main__":
 
    arr = [3, 2, 1, 4]
    N = len(arr)
 
    # Function Call
    minSubarray(arr, N)
 
# This code is contributed by Chitranayal


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
public class pair
{
  public int first,
  second;
  public pair(int first,
              int second) 
  {
    this.first = first;
    this.second = second;
  }   
}
 
// Function to count subarrays
// for each element where it is
// the minimum
static void minSubarray(int []arr,
                        int N)
{
  int []result = new int[N];
  Stack l = new Stack();
  Stack r = new Stack();
 
  // For the length of strictly
  // larger numbers on the left
  // of A[i]
  for(int i = 0; i < N; i++)
  {
    int count = 1;
    while (l.Count != 0 &&
           l.Peek().first > arr[i])
    {
      count += l.Peek().second;
      l.Pop();
    }
    l.Push(new pair(arr[i],
                    count));
 
    // Storing x in result[i]
    result[i] = count;
  }
 
  // For the length of strictly
  // larger numbers on the right
  // of A[i]
  for(int i = N - 1; i >= 0; i--)
  {
    int count = 1;
    while (r.Count != 0 &&
           r.Peek().first >= arr[i])
    {
      count += r.Peek().second;
      r.Pop();
    }
    r.Push(new pair(arr[i],
                    count));
 
    // Store x*y in result array
    result[i] *= count;
  }
 
  // Print the result
  for(int i = 0; i < N; i++)
  {
    Console.Write(result[i] + " ");
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {3, 2, 1, 4};
  int N = arr.Length;
 
  // Function Call
  minSubarray(arr, N);
}
}
 
// This code is contributed by Princi Singh


输出
1 2 6 1 

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

高效方法:此方法基于下一个更大的元素和上一个更大的元素的概念。请按照以下步骤解决问题:

  1. 为了找到元素的最小值,首先找到xy ,其中xarr [i]左侧严格大于数字的长度, yarr [右侧]较大数字的长度。我]
  2. 因此, x * y是其中arr [i]最小的子数组的总数。
  3. 要查找xy,请使用具有下一个更大元素和上一个更大元素的概念的堆栈。
  4. 对于下一个更大的元素,创建一个成对的堆栈,并将第一个数组元素和一个计数器推入以将子数组成对计数到堆栈中。
  5. 遍历数组并一一挑选数组元素:
    • 如果当前的数组元素比堆栈的顶部元件更大,则对于在堆栈顶部元件,当前元素是下一个元素更大。所以,弹出堆栈的顶部元件和由递增计数器值的计数器的堆栈的顶部,然后下一个栈顶元件与当前的数组元素等进行比较。
    • 否则,将带有计数器的当前数组元素推入堆栈,然后将计数器插入结果数组。
  6. 对上一个更大的元素重复步骤4、5。
  7. 最后,打印结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to count subarrays
// for each element where it is
// the minimum
void minSubarray(int* arr, int N)
{
    int result[N];
    stack > l, r;
 
    // For the length of strictly larger
    // numbers on the left of A[i]
    for (int i = 0; i < N; i++) {
 
        int count = 1;
        while (!l.empty()
               && l.top().first > arr[i]) {
 
            count += l.top().second;
            l.pop();
        }
        l.push({ arr[i], count });
 
        // Storing x in result[i]
        result[i] = count;
    }
 
    // For the length of strictly larger
    // numbers on the right of A[i]
    for (int i = N - 1; i >= 0; i--) {
 
        int count = 1;
        while (!r.empty()
               && r.top().first >= arr[i]) {
 
            count += r.top().second;
            r.pop();
        }
        r.push({ arr[i], count });
 
        // Store x*y in result array
        result[i] *= count;
    }
 
    // Print the result
    for (int i = 0; i < N; i++) {
 
        cout << result[i] << " ";
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { 3, 2, 1, 4 };
    int N = sizeof(arr) / sizeof(int);
 
    // Function Call
    minSubarray(arr, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
static class pair
{
    int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
 
// Function to count subarrays
// for each element where it is
// the minimum
static void minSubarray(int []arr, int N)
{
    int []result = new int[N];
    Stack l = new Stack<>();
    Stack r = new Stack<>();
 
    // For the length of strictly larger
    // numbers on the left of A[i]
    for(int i = 0; i < N; i++)
    {
        int count = 1;
        while (!l.isEmpty() &&
                l.peek().first > arr[i])
        {
            count += l.peek().second;
            l.pop();
        }
        l.add(new pair(arr[i], count));
 
        // Storing x in result[i]
        result[i] = count;
    }
 
    // For the length of strictly larger
    // numbers on the right of A[i]
    for(int i = N - 1; i >= 0; i--)
    {
        int count = 1;
        while (!r.isEmpty() &&
                r.peek().first >= arr[i])
        {
            count += r.peek().second;
            r.pop();
        }
        r.add(new pair(arr[i], count));
         
        // Store x*y in result array
        result[i] *= count;
    }
 
    // Print the result
    for(int i = 0; i < N; i++)
    {
        System.out.print(result[i] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 1, 4 };
    int N = arr.length;
 
    // Function Call
    minSubarray(arr, N);
}
}
 
// This code is contributed by Amit Katiyar

Python3

# Python3 program for the
# above approach
 
# Function to count subarrays
# for each element where it is
# the minimum
def minSubarray(arr, N):
   
    result = [0] * N
    l = []
    r = []
 
    # For the length of strictly
    # larger numbers on the left
    # of A[i]
    for i in range(N):
        count = 1;
        while (len(l) != 0 and
               l[-1][0] > arr[i]):
            count += l[-1][1]
            l.pop()
 
        l.append([arr[i], count])
 
        # Storing x in result[i]
        result[i] = count;
 
    # For the length of
    # strictly larger
    # numbers on the
    # right of A[i]
    for i in range(N - 1,
                   -1, -1):
        count = 1;
        while (len(r) != 0 and
               r[-1][0] >= arr[i]):
            count += r[-1][1]
            r.pop();
 
        r.append([arr[i], count]);
 
        # Store x*y in result
        # array
        result[i] *= count
 
    # Print the result
    for i in range(N):
        print(result[i],
              end = " ")
 
# Driver Code
if __name__ == "__main__":
 
    arr = [3, 2, 1, 4]
    N = len(arr)
 
    # Function Call
    minSubarray(arr, N)
 
# This code is contributed by Chitranayal

C#

// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
public class pair
{
  public int first,
  second;
  public pair(int first,
              int second) 
  {
    this.first = first;
    this.second = second;
  }   
}
 
// Function to count subarrays
// for each element where it is
// the minimum
static void minSubarray(int []arr,
                        int N)
{
  int []result = new int[N];
  Stack l = new Stack();
  Stack r = new Stack();
 
  // For the length of strictly
  // larger numbers on the left
  // of A[i]
  for(int i = 0; i < N; i++)
  {
    int count = 1;
    while (l.Count != 0 &&
           l.Peek().first > arr[i])
    {
      count += l.Peek().second;
      l.Pop();
    }
    l.Push(new pair(arr[i],
                    count));
 
    // Storing x in result[i]
    result[i] = count;
  }
 
  // For the length of strictly
  // larger numbers on the right
  // of A[i]
  for(int i = N - 1; i >= 0; i--)
  {
    int count = 1;
    while (r.Count != 0 &&
           r.Peek().first >= arr[i])
    {
      count += r.Peek().second;
      r.Pop();
    }
    r.Push(new pair(arr[i],
                    count));
 
    // Store x*y in result array
    result[i] *= count;
  }
 
  // Print the result
  for(int i = 0; i < N; i++)
  {
    Console.Write(result[i] + " ");
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {3, 2, 1, 4};
  int N = arr.Length;
 
  // Function Call
  minSubarray(arr, N);
}
}
 
// This code is contributed by Princi Singh
输出
1 2 6 1 

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