Given an array A of n integers. The task is to find the sum of minimum of all possible (contiguous) subarray of A.
Input: A = [3, 1, 2, 4]
Explanation: Subarrays are , , , , [3, 1], [1, 2], [2, 4], [3, 1, 2], [1, 2, 4], [3, 1, 2, 4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
Input : A = [1, 2, 3, 4]
Output : 20
Approach: The Naive approach is to generate all possible (contiguous) subarrays, find their minimum and add them to result. The time complexity will be O(N2).
Efficient Approach: The general intuition for solution to the problem is to find sum(A[i] * f(i)), where f(i) is the number of subarrays in which A[i] is the minimum.
In order to find f[i], we need to find out:
left[i], the length of strictly larger numbers on the left of A[i],
right[i], the length of larger numbers on the right of A[i].
We make two arrays left[ ] and right[ ] such that:
left[i] + 1 equals to the number of subarrays ending with A[i], and A[i] is only single minimum.
Similarly, right[i] + 1 equals to the number of subarrays starting with A[i], and A[i] is first minimum.
Finally, f(i) = (left[i]) * (right[i]), where f[i] equals total number of subarrays in which A[i] is minimum.
Below is the implementation of above approach
Time Complexity: O(N), where N is the length of A.
Space Complexity: O(N).
- Sum of minimum and maximum elements of all subarrays of size k.
- Flip minimum signs of array elements to get minimum sum of positive elements possible
- Number of subarrays whose minimum and maximum are same
- Subarrays with distinct elements
- Count subarrays with same even and odd elements
- Sum of minimum element of all subarrays of a sorted array
- Minimum absolute difference of XOR values of two subarrays
- Count of subarrays having exactly K distinct elements
- Count subarrays with all elements greater than K
- Count Subarrays with Consecutive elements differing by 1
- Count subarrays with equal number of occurrences of two given elements
- Count subarrays such that remainder after dividing sum of elements by K gives count of elements
- Count subarrays having total distinct elements same as original array
- Minimum elements to change so that for an index i all elements on the left are -ve and all elements on the right are +ve
- Differences between number of increasing subarrays and decreasing subarrays in k sized windows
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.