Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
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:

C++
<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 1:35am
Comments
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?

1 solution

C++
#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;
}
 
Share this answer
 
Comments
KarstenK 5-Oct-18 12:39pm    
Nice homework ;-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900