forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Balanced_array.cpp
94 lines (82 loc) · 1.77 KB
/
Balanced_array.cpp
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
Description :
An array of even size, task is to find minimum value that can be
added to an element so that array become balanced. An array is
balanced if the sum of the left half of the array elements is
equal to the sum of right half.
*/
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int minValueToBalance(int a[], int n)
{
//first half sum
int f_sum = 0;
//second half sum
int s_sum = 0;
int mid = n / 2;
int result = 0;
//for first half of an array
for (int i = 0; i < mid; i++)
{
f_sum += a[i];
}
//for second half of an array
for (int j = mid; j < n; j++)
{
s_sum += a[j];
}
if (f_sum > s_sum)
{
result = f_sum - s_sum;
}
else
{
result = s_sum - f_sum;
}
return result;
}
};
int main()
{
int size;
cout << "Enter the lenght of an array : " << endl;
cin >> size;
int a[size];
cout << "Enter " << size << " number of elements in array :" << endl;
for (auto i = 0; i < size; i++)
{
cin >> a[i];
}
Solution obj;
cout << "To make the array balanced you can add : " << endl;
cout << obj.minValueToBalance(a, size);
return 0;
}
/*
Time complexity : O(n)
Space complexity : O(n)
*/
/*
Test Cases:
Test Case 1 :
Input :
Enter the lenght of an array :
4
Enter 4 number of elements in array :
1 5 3 2
Output:
To make the array balanced you can add :
1
Test case 2:
Input :
Enter the lenght of an array :
6
Enter 6 number of elements in array :
1 2 1 2 1 3
Output :
To make the array balanced you can add :
2
*/