topic
[Problem description]
In the sequence a_1, a_2, …, a_n, define the distance between two elements a_i and a_j as |ij|+|a_i-a_j|, that is, the absolute value of the distance of the element subscript plus the difference of the element value, Where |x| represents the absolute value of x.
Given a sequence of numbers, find out the largest element distance between elements.
[Input format]
The first line of input contains an integer n.
The second line contains n integers a_1, a_2, …, a_n, and adjacent integers are separated by spaces to indicate a given sequence of numbers.
[Output format] The
output line contains an integer to indicate the answer.
[Sample input]
5
9 4 2 4 7
[Sample output]
9
[Sample description]
The distance between a_1 and a_3 is |1-3|+|9-2|=9.
[Evaluation use case scale and convention]
For 50% of the evaluation use cases, 2 <= n <= 100, 0 <= number in the sequence <= 1000.
For all evaluation cases, 2 <= n <= 1000, 0 <= number in the series <= 10000.
hint
The arrays with subscript 0 are not involved in the operation, and n+1 is required when creating the array,
such as int arr[] = new int[n+1];
Problem solving ideas
Separately define a method to get the absolute value, call this method whenever you want to get the absolute value
Code
import java.util.Scanner;
public class Main {
//蓝桥杯要求class命名为Main,且无package
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt();
int arr[] = new int[n+1];
int max=0;
for(int i=1;i<n+1;i++){
arr[i]=scanner.nextInt();
}
for(int i=1;i<n+1;i++){
for(int j=i+1;j<n+1;j++){
int distance = f(j,i)+f(arr[i],arr[j]); //distance代表距离
if(distance>max){
max=distance;
}
}
}
System.out.println(max);
}
public static int f(int a,int b){
//取绝对值
return a>=b?a-b:b-a; //返回绝对值
}
}