公式

A - Maximal Value 解説 by en_translator


If you are new to learning programming and do not know where to start, please try Problem A “Welcome to AtCoder” from practice contest. There you can find a sample code for each language.
Also, if you are not familiar with problems in programming contests, we recommend you to try some problems in “AtCoder Beginners Selection” (https://atcoder.jp/contests/abs).


Count the number of indices \(i\) satisfying the condition.

The answer can be found by the following algorithm:

  • Let \(\text{ans}=0\).
  • For \(i=1,2,\ldots,N-2\) in order, do the following:
    • If \(A_{i}<A_{i+1}>A_{i+2}\), add \(1\) to \(\text{ans}\).
  • Print \(\text{ans}\).

Sample code (Python3)

n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(n - 2):
    ans += a[i] < a[i + 1] > a[i + 2]
print(ans)

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;
int main() {
	int n;
	cin >> n;
	vector<int> a(n);
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	int ans = 0;
	for (int i = 0; i < n - 2; i++) {
		if (a[i] < a[i + 1] && a[i + 1] > a[i + 2]) {
			ans++;
		}
	}
	cout << ans << endl;
	return 0;
}

投稿日時:
最終更新: