Problem Statement:
Given an unsorted array, you need to find 3 elements whose sum is the minimum.
Example:
arr = {-1, 2, 3, -2}; Output: -1 The elements are: -1, -2, 2
The solution in very simple, take 3 variables that will hold minimum, second minimum and third minimum element present in the array and print the sum of these three elements.
Solution in C++
#include <vector> #include <algorithm> //visit www.ProDeveloperTutorial.com for 450+ solved questions #include <iostream> #include <queue> using namespace std; void get_min_sum(int arr[] , int n) { int f_min = 99999999; int s_min = 99999999; int t_min = 99999999; for (int i = 0; i < n; i++) { // get the first, second and third min elements if (arr[i] < f_min) { t_min = s_min; s_min = f_min; f_min = arr[i]; } // update second and third min elements else if (arr[i] < s_min) { t_min = s_min; s_min = arr[i]; } else if (arr[i] < t_min) { t_min = arr[i]; } } cout<< "The 3 numbers are"<<f_min <<" "<< s_min <<" " << t_min<<". The sum is = "<< f_min + s_min + t_min; } int main() { int arr1[] ={-1, 2, 3, -2}; get_min_sum(arr1, 4); }
Output:
The 3 numbers are-2 -1 2. The sum is = -1