/
Robot_battery.cpp
64 lines (58 loc) · 1.54 KB
/
Robot_battery.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
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <algorithm>
#include <cassert>
#include <iostream>
#include <limits>
#include <random>
#include <vector>
using std::cout;
using std::default_random_engine;
using std::endl;
using std::max;
using std::min;
using std::numeric_limits;
using std::random_device;
using std::uniform_int_distribution;
using std::vector;
// @include
template <typename HeightType>
HeightType find_battery_capacity(const vector<HeightType>& h) {
HeightType min_height = numeric_limits<HeightType>::max(), capacity = 0;
for (const HeightType &height : h) {
capacity = max(capacity, height - min_height);
min_height = min(min_height, height);
}
return capacity;
}
// @exclude
// O(n^2) checking answer
template <typename HeightType>
HeightType check_ans(const vector<HeightType>& h) {
HeightType cap = 0;
for (int i = 1; i < h.size(); ++i) {
for (int j = 0; j < i; ++j) {
cap = max(cap, h[i] - h[j]);
}
}
return cap;
}
int main(int argc, char *argv[]) {
default_random_engine gen((random_device())());
for (int times = 0; times < 1000; ++times) {
int n;
if (argc == 2) {
n = atoi(argv[1]);
} else {
uniform_int_distribution<int> dis(1, 10000);
n = dis(gen);
}
vector<int> A;
uniform_int_distribution<int> dis(0, numeric_limits<int>::max());
for (int i = 0; i < n; ++i) {
A.emplace_back(dis(gen));
}
cout << find_battery_capacity(A) << endl;
assert(check_ans(A) == find_battery_capacity(A));
}
return 0;
}