-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStick Lengths.cpp
More file actions
79 lines (59 loc) · 1.67 KB
/
Stick Lengths.cpp
File metadata and controls
79 lines (59 loc) · 1.67 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <bits/stdc++.h>
using namespace std;
const long long MOD= 1e9+7;
const int N = 1e5+10;
long long computeCost(long long arr[], int N, long long X)
{
long long cost = 0;
for (int i = 0; i < N; i++)
cost += abs(arr[i] - X);
return cost;
}
// Method to find minimum cost to make all
// elements equal
long long minCostToMakeElementEqual(long long arr[], int N)
{
long long low, high;
low = high = arr[0];
// setting limits for ternary search by
// smallest and largest element
for (int i = 0; i < N; i++) {
if (low > arr[i])
low = arr[i];
if (high < arr[i])
high = arr[i];
}
/* loop until difference between low and high
become less than 3, because after that
mid1 and mid2 will start repeating
*/
while ((high - low) > 2) {
// mid1 and mid2 are representative array
// equal values of search space
long long mid1 = low + (high - low) / 3;
long long mid2 = high - (high - low) / 3;
long long cost1 = computeCost(arr, N, mid1);
long long cost2 = computeCost(arr, N, mid2);
// if mid2 point gives more total cost,
// skip third part
if (cost1 < cost2)
high = mid2;
// if mid1 point gives more total cost,
// skip first part
else
low = mid1;
}
// computeCost gets optimum cost by sending
// average of low and high as X
return computeCost(arr, N, (low + high) / 2);
}
int main(){
int n;
cin>>n;
long long a[n];
for(int i=0;i<n;i++)
cin>>a[i];
long long ans=minCostToMakeElementEqual(a,n);
cout<<ans<<endl;
return 0;
}