1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <iostream>
#include <vector>
class Solution
{
private:
std::vector<int> array;
public:
Solution(std::vector<int>&);
int add(int, int);
bool swap(int&, int&);
void solve();
};
Solution::Solution(std::vector<int>& anArray){array = anArray;};
int Solution::add(int a, int b) { return a + b; }
bool Solution::swap(int &a, int &b)
{
int temp{a};
if( a > b)
{
a = b;
b = temp;
return true;
}
return false;
}
void Solution::solve()
{
int first{array[0]}, second{array[1]};
swap(first,second);
int maximum_sum{add(first,second)};
int trial_sum{0};
for(int i = 2; i < array.size(); i++)
{
trial_sum = add(array[i], second);
if( swap(trial_sum, maximum_sum) )
{
first = array[i];
swap(first,second);
}
}
std::cout
<< "Maximum: " << first << '+' << second << '=' << maximum_sum << '\n';
}
int main()
{
std::vector<int> arr_1{122,117,28,9,1,27,6,111,322};
std::vector<int> arr_2{5,9,7,11};
Solution sol_1(arr_1);
sol_1.solve();
Solution sol_2(arr_2);
sol_2.solve();
return 0;
}
| |