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
|
int solution(std::vector<int>& A) {
if (A.size() < 3) return 0;
bool all_positive{ true };
for (size_t i = 1; i < A.size() - 1; ++i)
if (A[i] < 0) all_positive = false; // Some element(s) inside the range
// [1, size -2] is/are not posititve
if (all_positive) {
int min_element = *std::min_element(A.begin() + 1, A.end() - 1);
size_t max_triple{ 0 };
for (int a : A)
max_triple += a;
return max_triple - A[0] - min_element - A[A.size() - 1];
}
int first_side_max{ 0 }, second_side_max{ 0 }, temp{ A[1] };
for (size_t i = 2; i < A.size() - 1; ++i)
if (temp < 0 && A[i] >= 0)
temp = A[i];
else if (temp + A[i] >= temp)
temp += A[i];
else if (temp > std::min(first_side_max, second_side_max)) {
(first_side_max < second_side_max ? first_side_max : second_side_max) = temp;
temp = 0;
}
else if (++i < A.size() - 1) temp = A[i];
if (temp > std::min(first_side_max, second_side_max)) // catch 'temp' remained in the loop
(first_side_max < second_side_max ? first_side_max : second_side_max) = temp;
return first_side_max + second_side_max;
}
int main()
{
std::vector<std::vector<int>> vec {
{-2, 1, 1, 3, 4, 8, 7}, // 16
{3, 5, 6, -3, 7, 1, 4, 2}, // 23
{3, 2, 6, -1, 4, 5, -1, 2}, // 17
{5, 17, 0, 3}, // 17
{-2, -3, -4, 1, -5, -6, -7}, // 1
{ -2, -3, -5, -1, -4, -8, -6}, // 0
{ 4, 5, 1, -3, 2, 1}, // 8
{-3, -5, 2, 3, 4, 5}, // 9
{1, 2, 3, 4, 5, 6} // 12
};
for (auto& v : vec)
std::cout << solution(v) << '\n';
}
|