C++ Tape Equilibrium
#include <cstdlib>
#include <limits>
#include <numeric>
#include <vector>
long long tapeEquilibrium(const std::vector<int>& a)
{
long long firstPart = 0;
long long secondPart = std::accumulate(a.begin(), a.end(), 0LL);
long long min = std::numeric_limits<long long>::max();
for (std::size_t i = 0; i + 1 < a.size(); ++i) {
// index `i` rather than `a[i]` here.
firstPart += static_cast<long long>(i);
secondPart -= static_cast<long long>(i);
long long difference = std::llabs(firstPart - secondPart);
min = std::min(min, difference);
}
return min;
}
This keeps left and right running sums and updates the smallest difference at each split point.
C++ Triangle
#include <algorithm>
#include <vector>
int triangle(std::vector<int> a)
{
std::sort(a.begin(), a.end());
int c = static_cast<int>(a.size());
if (c < 3) {
return 0;
}
for (int i = 0; i < c - 2; ++i) {
if (a[i] > 0 && a[i] > (a[i + 2] - a[i + 1])) {
return 1;
}
}
return 0;
}
This sorts the values and checks nearby triples, because a valid triangle only needs one local match after sorting.