Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POTD_12_OCT_2024_TwoSmallestsInEverySubarray #218

Merged
merged 1 commit into from
Oct 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;

}
};
Loading