Reputation: 3
This below is my code for adding 4 elements of vector arr and then printing the min-sum and the max-sum. This below is my code. Though after using unsigned long long of which the range is 0 to 18,446,744,073,709,551,615 to be precise. I am getting an integer overflow answer when the test case is 256741038 623958417 467905213 714532089 938071625. According to me, the answer should be in the limit of u-l-l. Please help me to better understand the cause.
void miniMaxSum(vector<int> arr) {
vector<int> A;
for(int i=0;i<5;i++){
unsigned long long int ans=0;
for(int j=0;j<5;j++){
if(i==j) continue;
else ans+=arr[j];
}
A.push_back(ans);
}
sort(A.begin(), A.end());
cout<<A[0]<<" "<<A[4];
}
Upvotes: 0
Views: 458
Reputation: 764
There is a couple of "issues" with this code, I'd suggest to make a few changes:
void miniMaxSum(const std::vector<int>& arr)
arr
, and then go over arr
again and subtract each
element from the total sum to get your answer.int
s, you'd not use unsigned int to hold results, so that your code will also work for negative integers as
input.arr.size()
instead.The following is the modified code, which is in Log(N) complexity.
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
void miniMaxSum(const std::vector<int>& arr) {
vector<int64_t> A;
int64_t sum = std::accumulate(arr.begin(), arr.end(), 0ull);
int64_t min_sum = LLONG_MAX;
int64_t max_sum = LLONG_MIN;
for(int i=0;i<arr.size();i++){
int64_t v = sum - arr[i];
if (v < min_sum) min_sum = v;
if (v > max_sum) max_sum = v;
}
cout<<min_sum<<" "<<max_sum;
}
int main() {
vector<int> a{256741038, 623958417, 467905213, 714532089, 938071625};
miniMaxSum(a);
return 0;
}
Upvotes: 0
Reputation: 1201
vector<int> A;
is a vector of ints. When you A.push_back(ans);
, ans
gets converted to int
, which results in overflow.
Just changing the declaration of A
to vector<unsigned long long int> A;
fixes the issue
Upvotes: 3