869869. Two Smallests in Every Subarray
Easy
Two Smallests in Every Subarray
Summary
The problem is about finding the sum of the two smallest elements in every subarray of a given array. This problem involves the concept of sliding window and array manipulation.
Detailed Explanation
To solve this problem, we can use a simple sliding window approach. We initialize our minimum values to the first element of the array. Then, for each subsequent element, we update the minimum values if necessary. The sum of these two smallest elements is then added to our total sum.
Here's a step-by-step breakdown of the solution:
- Initialize two variables
min1andmin2to the first element of the array. - Iterate through the array from the second element to the end.
- Update
min1if necessary (i.e., if the current element is smaller thanmin1). - If
min1has been updated, updatemin2with the value ofmin1. Otherwise, simply assign the current element tomin2. - Add the sum of
min1andmin2to our total sum. - Repeat steps 2-5 for each subarray.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only use a constant amount of space.
Here's an ASCII art diagram representing the sliding window:
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
^ ^
| min1 |
| min2 |
Optimized Solutions
Java
public int maximumSum(int[] arr) {
int n = arr.length;
long sum = 0;
int min1 = arr[0];
int min2 = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min1) {
min2 = min1;
min1 = arr[i];
} else if (arr[i] < min2 && arr[i] != min1) {
min2 = arr[i];
}
sum += Math.min(min1, min2);
}
return (int) sum;
}