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:

  1. Initialize two variables min1 and min2 to the first element of the array.
  2. Iterate through the array from the second element to the end.
  3. Update min1 if necessary (i.e., if the current element is smaller than min1).
  4. If min1 has been updated, update min2 with the value of min1. Otherwise, simply assign the current element to min2.
  5. Add the sum of min1 and min2 to our total sum.
  6. 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.