Metropolis to Beach - NZIC 2023 Round 3 Tutorial
This problem comes from New Zealand Olympiad in Informatics (NZOI) 2023 Round 3. For the problem statement refer to here: Metropolis to Beach.
This is an easy problem, hence I’ll jump straight to the solution.
1. Algorithm
This problem basically asks you to calculate the sum of the longest consecutive positive numbers.
Hence this is my solution:
- Initialize two variables,
uphillandmax_uphill:
uphillstores the sum of consecutive positive numbers andup_hillstores the maximum one. - If the block is positive, add this block to
uphill. - Else if the block is negative or we are at the end, find the maximum between
uphillandmax_uphill, and setup_hillto zero. - Return
max_uphill.
2. C++ Solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
int block;
int uphill = 0;
int max_uphill = -1;
for (int i = 0; i <= N; i++) {
cin >> block;
if (block > 0 and i < N) {
uphill += block;
} else {
if (uphill > 0) {
max_uphill = max(uphill, max_uphill);
uphill = 0;
}
}
}
cout << max_uphill << endl;
return 0;
}