题目来源:码蹄集
题目介绍:
B站老师思路讲解:https://www.bilibili.com/video/BV1vY411B7jg/?t=1958.7&vd_source=3ae2a916df1bc5c1114c2bf3e95a2118
Python代码实现:
参考链接:https://blog.51cto.com/u_15745546/5950627
def main():
#code here
arr = list(map(int,input().split()))
n = len(arr)
dp = [0]*n
for i in range(2,n):
if arr[i]-arr[i-1] == arr[i-1]-arr[i-2]:
if dp[i-1] != 0:
dp[i] = dp[i-1] +1
else:
dp[i] = 3
tot = 0
for i in range(2,n):
if dp[i] >= 3:
tot += dp[i]-3+1
print(tot)
if __name__ == '__main__':
main();
提交测试结果:
C++代码实现:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> arr;
int num;
while (cin >> num) {
arr.push_back(num);
}
int n = arr.size();
vector<int> dp(n, 0);
for (int i = 2; i < n; i++) {
if (arr[i] - arr[i - 1] == arr[i - 1] - arr[i - 2]) {
if (dp[i - 1] != 0) {
dp[i] = dp[i - 1] + 1;
} else {
dp[i] = 3;
}
}
}
int tot = 0;
for (int i = 2; i < n; i++) {
if (dp[i] >= 3) {
tot += dp[i] - 3 + 1;
}
}
cout << tot << endl;
return 0;
}
提交测试结果:
Java代码实现:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input = sc.nextLine().split(" ");
int[] arr = new int[input.length];
for (int i = 0; i < input.length; i++) {
arr[i] = Integer.parseInt(input[i]);
}
int n = arr.length;
int[] dp = new int[n];
for (int i = 2; i < n; i++) {
if (arr[i] - arr[i - 1] == arr[i - 1] - arr[i - 2]) {
if (dp[i - 1] != 0) {
dp[i] = dp[i - 1] + 1;
} else {
dp[i] = 3;
}
}
}
int tot = 0;
for (int i = 2; i < n; i++) {
if (dp[i] >= 3) {
tot += dp[i] - 3 + 1;
}
}
System.out.println(tot);
sc.close();
}
}