Input:4
Input: 4 2 3 6
Output :29
Explanation:
- sort the array and then add 2+3=5 now we have 5 4 6
- Next we add 5+4=9 now we have 9 and 6
- next we add 9+6=15 and finally we return 29 as solution which is sum of 5+9+15=29
I have to write a code for the same.
Here is my code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num;
cin >> num;
vector<int> box;
for (int i = 0; i < num; i++)
{
int temp;
cin >> temp;
box.push_back(temp);
}
sort(box.begin(), box.end());
vector<int> res;
int sum = box[0];
if (box.size() == 1)
{
cout << sum;
}
else
{
for (int i = 1; i < box.size(); i++)
{
sum = sum + box[i];
res[i] = sum;
}
res[0] = 0;
int result = 0;
for (int i = 0; i < res.size(); i++)
{
result += res[i];
}
cout << result;
}
}
The code is not working properly and is running into errors can someone help..? The question seems to be simple but I am unable to come up with and efficient solution for the same.