Two Smallests in Every Subarray
? Short Summary:
In today's CODE OF THE DAY, we tackle how to find the maximum sum of the two smallest elements in adjacent pairs of a subarray. This problem combines array manipulation and optimization techniques for an efficient solution! ????
Question:
Given an array of integers, the task is to find the maximum sum of the smallest and second smallest element among all possible subarrays of size greater than one. If the array size is too small to form a subarray, return -1.
?? Problem Breakdown:
Imagine having an array of integers, and you need to figure out the best sum that can be achieved by selecting two smallest elements from subarrays of size greater than one. It sounds tricky, but with the right approach, it can be solved efficiently! ??
Example:
?? Input: arr = [4, 3, 1, 5, 6]
?? Explanation:
You need to evaluate each subarray and find the sum of the two smallest numbers within those subarrays:
?? Output: 11
Optimal Solution Approach:
Code Implementation:
class Solution
{
public int pairWithMaxSum(int[] arr)
{
if(arr.length < 2)
{
return -1;
}
int n = arr.length;
int max = Integer.MIN_VALUE;
for(int i = 0; i < n-1; i++)
{
int sum = arr[i] + arr[i+1];
max = Math.max(sum, max);
}
return max;
}
}
?? How Does the Code Work?
?? Why This Approach?
This approach runs in O(n) time, making it super efficient even for large arrays. The space complexity is O(1), ensuring that it uses minimal memory, no matter the size of the input.