I made a function sumOfTwoSmallestNumbers()
that takes an integer vector (containing only positive values) and it returns the sum of the two lowest positive numbers stored in that vector. Unfortunately, my function fails for a few test cases (I do not have access to the inputs of those test cases). Please help me find the error in my code.
NOTE: Vector always consists of a minimum of 4 positive values
#include <iostream>
#include <vector>
using namespace std;
long sumOfTwoSmallestNumbers (vector<int> numbers)
{
long int sum = 0;
long int min1 = numbers[0];
int position;
for (unsigned long int i = 0; i < numbers.size(); i++){
if (numbers[i] < min1){
min1 = numbers[i];
position = i;
}
}
numbers.erase(numbers.begin() + position - 1);
long int min2 = numbers[0];
for (unsigned long int i = 0; i < numbers.size(); i++){
if (numbers[i] < min2){
min2 = numbers[i];
}
}
sum = min1 + min2;
return sum;
}
Logic: I have tried to first find the smallest value and store it in a variable and then remove that value from the vector. After that, I again searched for the smallest value in the vector and stored it in a variable. In end, I have added the two values and returned the sum.