Skip to content

Commit

Permalink
Merge pull request #218 from Avnee29/patch-9
Browse files Browse the repository at this point in the history
POTD_12_OCT_2024_TwoSmallestsInEverySubarray
  • Loading branch information
Gyanthakur authored Oct 29, 2024
2 parents 0e74a15 + cb02b47 commit 66874a9
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions POTD_12_OCT_2024_TwoSmallestsInEverySubarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Solution {
public:
int pairWithMaxSum(vector<int>& arr) {
// code here
int n = arr.size();

// Variable to store the maximum sum found
long maxSum = -1;

// Iterate over each element in the array except the
// last one
for (int i = 0; i < n - 1; i++) {

// Initialize the minimum element as the current
// element
int minn = arr[i];

// Initialize the second minimum element as the next
// element
int secondMinn = arr[i + 1];

// Iterate over the remaining elements in the array
for (int j = i + 1; j < n; j++) {
// Update the minimum and second minimum
// elements
if (minn >= arr[j]) {
secondMinn = minn;
minn = arr[j];
}
else if (secondMinn > arr[j]) {
secondMinn = arr[j];
}

// Calculate the current sum of the minimum and
// second minimum elements
long currSum = minn + secondMinn;

// Update the maximum sum if the current sum is
// greater
maxSum = max(maxSum, currSum);
}
}

// Return the maximum sum found
return maxSum;

}
};

0 comments on commit 66874a9

Please sign in to comment.