14,734,606 members
1.00/5 (1 vote)
See more:
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.

What I have tried:

<pre>#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;
}

}
Posted
Updated 4-Oct-18 2:35am
OriginalGriff 4-Oct-18 7:24am

And?
What does it do that you didn't expect, or not do that you did?
What have you tried to find out why?
Any error messages?
Where are you stuck?
What help do you need?

## Solution 1

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

int main()
{
size_t num;
cin >> num;
vector<int> box;

if (num < 1) return -1;

box.resize(num);

for(auto & x : box)
cin >> x;

sort(box.begin(), box.end());

vector<int> res;

int sum = box[0];

for (size_t i=1; i<num; ++i)
{
sum += box[i];
res.push_back(sum);
}

cout << accumulate(res.begin(), res.end(), 0) << endl;
}
KarstenK 5-Oct-18 12:39pm

Nice homework ;-)