-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinAbsSum.cpp
More file actions
57 lines (54 loc) · 1.56 KB
/
MinAbsSum.cpp
File metadata and controls
57 lines (54 loc) · 1.56 KB
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
// you can use includes, for example:
#include <algorithm>
#include <numeric>
#include <climits>
#include <stdlib.h>
#include <cmath>
#include <bitset>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
std::for_each(A.begin(), A.end(), [](int &n){ n = abs(n); });
//get the sum
//if(A.size() < 1)
// return 0;
//if(A.size() < 2)
// return A[0];
int sum = std::accumulate(A.begin(), A.end(), 0);
int max = *std::max_element(A.begin(), A.end());
//cout << sum << endl;
//for(int i)
//create container for possible values
int possible_results[sum];
int lowest_max_sum = sum;
//int S[A.size()] = {1};
for(int i = 0;i < pow(2,A.size());i++)
{
//cout << i << endl;
std::string binary = std::bitset<32>(i).to_string();
//cout << binary.substr(32-A.size(), 32) << endl;
std::string sub_bin = binary.substr(32-A.size(), 32);
int total = 0;
for(int j = 0;j < A.size();j++)
{
if(sub_bin[j] == '0')
total = total-A[j];
else
total = total+A[j];
}
if(abs(total) < lowest_max_sum)
{
lowest_max_sum = abs(total);
}
}
return lowest_max_sum;
/*for(int i = 0;i < A.size();i++)
{
if((S[i] == 1)&&((sum - 2*A[i]) > 0)
{
lowest_max_sum = min(lowest_max_sum, sum - 2*A[i])
}
}
return lowest_max_sum;*/
}