Search is not available for this dataset
name
stringlengths 2
112
| description
stringlengths 29
13k
| source
int64 1
7
| difficulty
int64 0
25
| solution
stringlengths 7
983k
| language
stringclasses 4
values |
---|---|---|---|---|---|
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(input())
a = list(map(int, input().split()))
b = []
for i in range(n - 1):
b.append(abs(a[i] - a[i + 1]))
c = []
s = 1
summ = 0
for i in range(n - 1):
summ += s * b[i]
s = -s
c.append(summ)
c.sort()
if c[0] < 0:
print(c[n - 2] - c[0])
else:
print(c[n - 2]) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n=int(input())
a=list(map(int,input().split()))
b=[abs(a[i]-a[i+1]) for i in range(n-1)]
p,q,r=0,0,0
for i in b:
_p=max(0,q+i)
_q=max(0,p-i)
p,q=_p,_q
r=max(p,q,r)
print(r) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long int find(vector<long long int> &x) {
int n = x.size(), i;
long long int mx_end = 0, mx_till = -1e15;
for (int i = 0; i < n; i++) {
mx_end = mx_end + x[i];
mx_till = max(mx_till, mx_end);
if (mx_end < 0) mx_end = 0;
}
return mx_till;
}
int main() {
long long int i, j, n, ans = INT_MIN, curr;
vector<long long int> vec;
j = 1;
cin >> n;
long long int arr[n + 9];
for (i = 0; i < n; i++) cin >> arr[i];
for (i = 1; i < n; i++) {
vec.push_back(abs(arr[i] - arr[i - 1]) * j);
j = -j;
}
curr = 0;
vector<long long int> vec1;
long long int ans1 = INT_MIN;
for (i = 0; i < vec.size(); i++) {
vec1.push_back(vec[i] * -1);
}
cout << max(find(vec1), find(vec));
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import math as mt
import sys
import bisect
input=sys.stdin.readline
#t=int(input())
def takeSecond(elem):
return elem[1]
def gcd(a,b):
if (b == 0):
return a
return gcd(b, a%b)
def kadane(l):
#print(l)
maxim=sum(l[:])
curr=0
for i in range(len(l)):
curr+=l[i]
maxim=max(curr,maxim)
if curr<0:
curr=0
return maxim
t=1
for _ in range(t):
n=int(input())
#b,q,maxi,m=map(int,input().split())
l=list(map(int,input().split()))
l1=[]
ch=0
for i in range(n-1):
l1.append(abs(l[i+1]-l[i]))
if ch%2!=0:
l1[-1]*=-1
ch+=1
maxi=kadane(l1)
ch=0
for i in range(1,n-1):
l1[i]*=-1
maxi=max(maxi,kadane(l1[1:]))
print(maxi) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Mayank
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
int[] b = new int[n - 1];
for (int i = 0; i < n - 1; i++)
b[i] = (i % 2 == 0 ? 1 : -1) * StrictMath.abs(a[i] - a[i + 1]);
long[] s = new long[n - 1];
s[0] = b[0];
for (int i = 1; i < n - 1; i++)
s[i] += s[i - 1] + b[i];
long mi = 0, ma = 0;
for (int i = 0; i < n - 1; i++) {
if (mi > s[i])
mi = s[i];
if (ma < s[i])
ma = s[i];
}
out.print(StrictMath.abs(mi - ma));
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.Scanner;
public class Main {
private static long[][] dp = new long[100010][2];
private static long[] input = new long[100010];
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int i , j , n = scan.nextInt();
long ans = Long.MIN_VALUE;
for (i = 0;i < n;i ++) {
input[i] = scan.nextLong();
}
for (i = n - 2;i >= 0;i --) {
dp[i][0] = Math.abs(input[i] - input[i + 1]);
dp[i][1] = - Math.abs(input[i] - input[i + 1]);
if (dp[i + 1][0] >= 0) {
dp[i][1] += dp[i + 1][0];
}
if (dp[i + 1][1] >= 0) {
dp[i][0] += dp[i + 1][1];
}
if (dp[i][0] > ans) {
ans = dp[i][0];
}
}
System.out.println(ans);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int a[100005];
long long dp[100005][2];
const long long inf = 1e16;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
dp[1][0] = abs(a[1] - a[2]);
dp[1][1] = -inf;
long long l = dp[1][1], r = dp[1][0];
long long ans = dp[1][0];
for (int i = 2; i < n; i++) {
dp[i][0] = abs(a[i] - a[i + 1]);
dp[i][1] = r - abs(a[i] - a[i + 1]);
dp[i][0] = max(dp[i][0], dp[i][0] + l);
r = dp[i][0];
l = dp[i][1];
ans = max(dp[i][0], ans);
ans = max(dp[i][1], ans);
}
cout << ans << endl;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int mod=(int)1e9+7;
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
int n=sc.nextInt();
long[] arr=new long[n+1];
for(int i=1;i<=n;i++)arr[i]=sc.nextInt();
long[] even=new long[n];
long[] odd=new long[n];
for(int i=1;i<n;i++){
odd[i]=Math.abs(arr[i]-arr[i+1])*(i%2==1?1:-1);
}
for(int i=2;i<n;i++){
even[i]=Math.abs(arr[i]-arr[i+1])*(i%2==0?1:-1);
}
long maxg=odd[1],currg=odd[1];
for(int i=2;i<n;i++){
currg=Math.max(currg+odd[i],odd[i]);
if(currg>maxg)maxg=currg;
}
if(n<=2){
System.out.println(maxg);
return;
}
currg=even[2];
for(int i=3;i<n;i++){
currg=Math.max(currg+even[i],even[i]);
if(currg>maxg)maxg=currg;
}
if(currg>maxg)maxg=currg;
System.out.println(maxg);
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
const long long INF = 1LL << 60LL;
int n;
int a[N], candidate[N];
long long res = -(INF);
inline void solve(int st) {
long long curPrefix = 0;
long long minPrefix = 0;
for (int i = st; i < n; i++) {
curPrefix += candidate[i];
res = max(res, curPrefix - minPrefix);
minPrefix = min(minPrefix, curPrefix);
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i < n; i++) {
candidate[i] = abs(a[i] - a[i + 1]);
if ((i % 2) == 0) {
candidate[i] *= -1;
}
}
solve(0);
for (int i = 1; i < n; i++) {
candidate[i] *= -1;
}
solve(1);
cout << res << "\n";
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n=input()
l=[0]+map(int,raw_input().split())
l=[0]+[abs(l[i]-l[i+1]) for i in range(1,n)]
ans=l[1]
sm1,sm2=0,0
for i in range(1,n):
if i%2:
temp = -l[i]
else:
temp=l[i]
sm1+=temp
sm2-=temp
ans=max(ans,sm1,sm2)
sm1=max(sm1,0)
sm2=max(sm2,0)
print ans
| PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
public class Functions{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int a[] = new int [n-1];
int ult = sc.nextInt();
for (int i=1;i<n;i++) {
int actual = sc.nextInt();
a[i-1] = Math.abs(ult-actual);
ult = actual;
}
long max = 0;
long sum = 0;
for (int i=0;i<n-1;i++) {
if (sum<0)
sum=0;
if (i%2==0)
sum += a[i];
else
sum -= a[i];
if (sum>max)
max = sum;
}
sum = 0;
for (int i=0;i<n-1;i++) {
if (sum<0)
sum=0;
if (i%2==1)
sum += a[i];
else
sum -= a[i];
if (sum>max)
max = sum;
}
System.out.println(max);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int tmp[] = new int[n];
int arr1[] = new int[n - 1];
int arr2[] = new int[n - 1];
for(int i = 0; i < n; ++i) tmp[i] = sc.nextInt();
for(int i = 0; i < n - 1; ++i) {
int next = Math.abs(tmp[i] - tmp[i + 1]);
arr1[i] = arr2[i] = next;
if((i & 1) == 0) arr1[i] *= -1;
else arr2[i] *= -1;
}
out.println(Math.max(kadane(arr1), kadane(arr2)));
out.flush();
out.close();
}
private static long kadane(int[] arr) {
long sum, max;
sum = max = arr[0];
for(int i = 1; i < arr.length; ++i) {
sum = Math.max(sum + arr[i], arr[i]);
max = Math.max(max, sum);
}
return max;
}
static class Scanner{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.Long.max;
import static java.lang.Math.*;
public class ProblemC {
BufferedReader rd;
ProblemC() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
rd.readLine();
long[] a = longarr();
long best = Long.MIN_VALUE;
for(int i=0;i<2;i++) {
long[] b = diff(a, i);
int n = b.length;
long sum = 0;
long minSum = 0;
for(int j=0;j<n;j++) {
sum += b[j];
best = max(best, sum - minSum);
minSum = min(minSum, sum);
}
}
out(best);
}
private long[] diff(long[] a, int s) {
int n = a.length;
long[] res = new long[n-s-1];
for(int i=0;i<res.length;i++) {
res[i] = abs(a[s+i] - a[s+i+1]) * (i%2==0?1:-1);
}
return res;
}
private long[] longarr() throws IOException {
return longarr(rd.readLine());
}
private long[] longarr(String s) {
String[] q = split(s);
int n = q.length;
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = Long.parseLong(q[i]);
}
return a;
}
private String[] split(String s) {
if(s == null) {
return new String[0];
}
int n = s.length();
int start = -1;
int end = 0;
int sp = 0;
boolean lastWhitespace = true;
for(int i=0;i<n;i++) {
char c = s.charAt(i);
if(isWhitespace(c)) {
lastWhitespace = true;
} else {
if(lastWhitespace) {
sp++;
}
if(start == -1) {
start = i;
}
end = i;
lastWhitespace = false;
}
}
if(start == -1) {
return new String[0];
}
String[] res = new String[sp];
int last = start;
int x = 0;
lastWhitespace = true;
for(int i=start;i<=end;i++) {
char c = s.charAt(i);
boolean w = isWhitespace(c);
if(w && !lastWhitespace) {
res[x++] = s.substring(last,i);
} else if(!w && lastWhitespace) {
last = i;
}
lastWhitespace = w;
}
res[x] = s.substring(last,end+1);
return res;
}
private boolean isWhitespace(char c) {
return c==' ' || c=='\t';
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemC();
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(input())
R = [int(i) for i in input().split()]
L = [abs(R[i]-R[i+1]) for i in range(n-1)]
ans = [0 for _ in range(n)]
ans[0] = L[0]
for i in range(1, n-1):
ans[i] = max(L[i], L[i]-ans[i-1])
if i - 2 >= 0:
ans[i] = max(ans[i], L[i]-L[i-1]+ans[i-2])
print(max(ans))
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(in, out);
out.close();
}
}
class TaskC {
public void solve(InputReader in, OutputWriter out) {
int n = in.nextInt();
long[] a = new long[n];
for(int i = 0; i < n; i++) {
a[i] = in.nextLong();
}
long ans = f(n, a);
long[] b = new long[n-1];
for(int i = 0; i < n-1; i++) {
b[i] = a[i+1];
}
long ans2 = (n-1 >= 2) ? f(n-1, b) : -Long.MAX_VALUE;
ans = Math.max(ans, ans2);
out.write(ans);
}
long f(int n, long[] a) {
long[] sum = new long[n];
sum[1] = Math.abs(a[0]-a[1]);
for(int i = 2; i < n; i++) {
if(i%2==0) {
sum[i] = sum[i-1] - Math.abs(a[i-1]-a[i]);
} else {
sum[i] = sum[i-1] + Math.abs(a[i-1]-a[i]);
}
}
long[] max = new long[n];
max[n-1] = sum[n-1];
for(int i = n-2; i>=0; i--)
max[i] = Math.max(sum[i], max[i+1]);
long ans = max[0];
long cur = 0;
for(int i=0; i < n-2; i+=2) {
cur += -Math.abs(a[i]-a[i+1])+Math.abs(a[i+1]-a[i+2]);
ans = Math.max(ans, max[i+2]+cur);
}
return ans;
}
}
class InputReader {
public InputReader(InputStream inputStream) {
tokenizer = null;
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
StringTokenizer tokenizer;
BufferedReader reader;
}
class OutputWriter {
public OutputWriter(OutputStream outputStream) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
outputStream)));
}
public void write(Object... o) {
for (Object x : o)
out.print(x);
}
public void writeln(Object... o) {
write(o);
out.println();
}
public void close() {
out.close();
}
PrintWriter out;
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
public class fagain{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] array = new long[n];
for(int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
long[] a = new long[n-1];
for (int i = 0; i < n-1; i++) {
a[i] = (long)(Math.abs(array[i]-array[i + 1]));
}
long max = a[0];
long x = a[0];
long y = 0;
for (int i = 1; i < n - 1; i++) {
if (i % 2 == 0) {
x += a[i];
y -= a[i];
if (y < 0) {
y = 0;
}
if (x > max) {
max = x;
}
}
else {
x -= a[i];
y += a[i];
if (x < 0) {
x = 0;
}
if (y > max) {
max = y;
}
}
}
System.out.println(max);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kronos
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
long max(long a, long b) {
return a > b ? a : b;
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
long[] a = new long[n - 1];
long x = in.nextLong(), y;
for (int i = 1; i < n; i++) {
y = in.nextLong();
if (i % 2 == 0) {
a[i - 1] = -Math.abs(x - y);
} else {
a[i - 1] = Math.abs(x - y);
}
x = y;
}
long ans = a[0];
long sum = 0;
for (int i = 0; i < n - 1; i++) {
sum += a[i];
ans = max(ans, sum);
sum = max(sum, 0);
//a[i] += a[i-1];
}
sum = 0;
for (int i = 1; i < n - 1; i++) {
sum += -a[i];
ans = max(ans, sum);
sum = max(sum, 0);
//a[i] += a[i-1];
}
out.println(ans);
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.InputMismatchException;
public class coco {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
InputReader in=new InputReader(System.in);
OutputWriter out=new OutputWriter(System.out);
int n=in.readInt();
long arr1[]=new long [n-1];
long arr2[]=new long [n-1];
long a[]=new long [n];
for(int i=0;i<n;i++){
a[i]=in.readInt();
if(i!=0){
long vv=Math.abs(a[i-1]-a[i]);
if(i%2==1){
arr1[i-1]=vv;
arr2[i-1]=-vv;}
else{
arr1[i-1]=-vv;
arr2[i-1]=vv;
}
}
}
out.printLine(Math.max(find_max(arr1, 0, n-2),find_max(arr2, 0, n-2) ));
out.close();
}
static long cross(long a[],int low,int mid,int high){
long leftsum=Long.MIN_VALUE;
long leftsum1=Long.MIN_VALUE;
long sum=0;
//long mostnegleft=0;
for(int i=mid;i>=low;i--){
sum=sum+a[i];
if(sum>leftsum1){
leftsum1=sum;
}
}
long rightsum=Long.MIN_VALUE;
long rightsum1=Long.MIN_VALUE;
sum=0;
//long mostnegright=0;
for(int i=mid+1;i<=high;i++){
sum=sum+a[i];
if(sum>rightsum1){
rightsum1=sum;
}
}
if(rightsum1<=0){
rightsum1=0;
}
return Math.max(0, leftsum1+rightsum1);
}
static long find_max(long a[],int low,int high){
if(high==low){
return a[low];
}
int mid=(low+high)/2;
long lm =find_max(a, low, mid);
long rm =find_max(a, mid+1, high);
long com=cross(a, low, mid, high);
com=Math.max(com, lm);
com=Math.max(com, rm);
return com;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;import java.io.*;import java.math.*;
public class Main
{
public static void process()throws IOException
{
int n=ni();
int[]A=nai(n);
int[]temp=new int[n-1];
for(int i=0;i<n-1;i++)
{
temp[i]=Math.abs(A[i+1]-A[i]);
if(i%2==1)
temp[i]=-temp[i];
}
long ans=0,curr=0;
for(int i=0;i<n-1;i++)
{
curr+=temp[i];
ans=Math.max(ans,curr);
curr=Math.max(curr,0);
}
// pn(Arrays.toString(temp));
for(int i=0;i<n-1;i++)
temp[i]=-temp[i];
curr=0;
for(int i=0;i<n-1;i++)
{
curr+=temp[i];
ans=Math.max(ans,curr);
curr=Math.max(curr,0);
}
pn(ans);
}
static AnotherReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
int t=1;
// t=ni();
while(t-->0) {process();}
out.flush();out.close();
}
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static void pni(Object o){out.println(o);out.flush();}
static int ni()throws IOException{return sc.nextInt();}
static long nl()throws IOException{return sc.nextLong();}
static double nd()throws IOException{return sc.nextDouble();}
static String nln()throws IOException{return sc.nextLine();}
static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class AnotherReader{BufferedReader br; StringTokenizer st;
AnotherReader()throws FileNotFoundException{
br=new BufferedReader(new InputStreamReader(System.in));}
AnotherReader(int a)throws FileNotFoundException{
br = new BufferedReader(new FileReader("input.txt"));}
String next()throws IOException{
while (st == null || !st.hasMoreElements()) {try{
st = new StringTokenizer(br.readLine());}
catch (IOException e){ e.printStackTrace(); }}
return st.nextToken(); } int nextInt() throws IOException{
return Integer.parseInt(next());}
long nextLong() throws IOException
{return Long.parseLong(next());}
double nextDouble()throws IOException { return Double.parseDouble(next()); }
String nextLine() throws IOException{ String str = ""; try{
str = br.readLine();} catch (IOException e){
e.printStackTrace();} return str;}}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
inline int read() {
int ans = 0, flag = 1;
char c;
c = getchar();
while (c < '0' || c > '9') {
if (c == '-') flag = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
ans = ans * 10 + (int)(c - '0');
c = getchar();
}
return ans * flag;
}
long long quickpow(long long x, long long y, long long mod) {
long long ans = x % mod;
while (y) {
if (y & 1) ans = ans * x % mod;
x = x * x % mod;
y >>= 1;
}
return ans;
}
long long num[maxn];
long long num1[maxn], num2[maxn];
long long dp[maxn];
int main() {
int n;
while (cin >> n) {
long long last;
long long ans = 0;
for (int i = 0; i < n; i++) num[i] = read();
for (int i = 0; i < n - 1; i++)
num1[i + 1] = abs(num[i + 1] - num[i]) * (i % 2 == 0 ? 1 : -1);
for (int i = 1; i < n - 1; i++)
num2[i] = abs(num[i + 1] - num[i]) * (i % 2 == 0 ? -1 : 1);
memset(dp, 0, sizeof dp);
for (int i = 1; i <= n - 1; i++) {
dp[i] = max(0LL, dp[i - 1]) + num1[i];
ans = max(ans, dp[i]);
}
memset(dp, 0, sizeof dp);
for (int i = 1; i <= n - 2; i++) {
dp[i] = max(0LL, dp[i - 1]) + num2[i];
ans = max(ans, dp[i]);
}
cout << ans << endl;
}
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int a[N], n;
long long pre[2], suf[2], sum[2];
long long divide(int L, int R) {
if (L == R) {
pre[0] = -a[L];
pre[1] = a[L];
return a[L];
}
int M = (L + R) / 2;
long long aa = divide(L, M);
long long bb = divide(M + 1, R);
long long ans = max(aa, bb);
int cur = 0;
suf[0] = suf[1] = 0;
for (int i = M; i >= L; --i) {
suf[(i - L) % 2] += a[i];
suf[(i - L + 1) % 2] -= a[i];
ans = max(ans, suf[(i - L) % 2] + pre[(M - i) % 2]);
}
pre[0] = pre[1] = LLONG_MIN;
sum[0] = sum[1] = 0;
for (int i = L; i <= R; ++i) {
for (int j = 0; j < 2; ++j) {
int sign = (2 * ((j + i - L) % 2) - 1);
sum[j] += sign * a[i];
pre[j] = max(pre[j], sum[j]);
}
}
return ans;
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
for (int i = 0; i < n - 1; ++i) a[i] = abs(a[i] - a[i + 1]);
cout << divide(0, n - 2) << '\n';
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int a[];
static long dp[][];
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader;
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(bufferedReader.readLine());
a = new int[N];
dp = new long[2][N];
String[] temp;
temp = bufferedReader.readLine().split(" ");
for (int i = 0; i < N; i++)
a[i] = Integer.parseInt(temp[i]);
System.out.println(solve());
}
private static long solveBrute(){
long max=0;
int N=a.length;
for(int l=0;l<N-2;l++){
for(int r=1;r<N-1;r++){
long count=0;
for(int i=l;i<r;i++)
count+= Math.abs(a[i]-a[i+1]) *Math.pow(-1,i-l);
if(count> max)
max=count;
}
}
return max;
}
private static long solve() {
//Check for sequence of even length
int N=a.length;
dp[0][N-1]=0;
dp[1][N-1]=0;
for(int i=N-2;i>=0;i--){
dp[0][i]=Math.abs(a[i]-a[i+1]);
if(i%2==0)
dp[1][i]=dp[0][i]-Math.min(dp[0][i+1],dp[1][i+1]);
else
dp[1][i]=dp[0][i]-Math.max(dp[0][i+1],dp[1][i+1]);
}
long count=0;
for(int i=0;i<N-1;i++){
if(dp[0][i]>count)
count=dp[0][i];
if(dp[1][i]>count)
count=dp[1][i];
}
//Check for sequence of odd length
dp[0][N-1]=0;
dp[1][N-1]=0;
for(int i=N-2;i>=0;i--){
dp[0][i]=Math.abs(a[i]-a[i+1]);
if(i%2==0)
dp[1][i]=dp[0][i]-Math.max(dp[0][i+1],dp[1][i+1]);
else
dp[1][i]=dp[0][i]-Math.min(dp[0][i+1],dp[1][i+1]);
}
long count2=0;
for(int i=0;i<N-1;i++){
if(dp[0][i]>count)
count2=dp[0][i];
if(dp[1][i]>count2)
count2=dp[1][i];
}
return Math.max(count,count2);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.InputMismatchException;
public class Solution {
public static void main(String[] args){
InputReader in=new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=in.readInt();
long[] arr=new long[n+1];
long[] arr1=new long[n+1];
long[] arr2=new long[n+1];
for(int i=1;i<=n;i++){
arr[i]=in.readLong();
}
for(int i=1;i<n;i++){
if(i%2==0)
{
arr1[i]=-1*Math.abs(arr[i+1]-arr[i]);
arr2[i]=Math.abs(arr[i+1]-arr[i]);
}
else{
arr1[i]=Math.abs(arr[i+1]-arr[i]);
arr2[i]=-1*Math.abs(arr[i+1]-arr[i]);
}
// pw.print(arr[i]+" ");
}
long x=Math.max(Max(arr1),Max(arr2));
pw.println(x);
pw.close();
}
static long Max(long[] a){
long max_so_far=a[0];
long curr_max=a[0];
for(int i=1;i<=a.length-2;i++){
curr_max=Math.max(a[i],curr_max+a[i]);
max_so_far=Math.max(max_so_far,curr_max);
}
return max_so_far;
}
static long fib(long n)
{
long F[][] = new long[][]{{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);
return F[0][0];
}
/* Helper function that multiplies 2 matrices F and M of size 2*2, and
puts the multiplication result back to F[][] */
static void multiply(long F[][], long M[][])
{
long x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
long y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
long z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
long w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x%1000000007;
F[0][1] = y%1000000007;
F[1][0] = z%1000000007;
F[1][1] = w%1000000007;
}
static void power(long F[][], long n)
{
long i;
long M[][] = new long[][]{{1,1},{1,0}};
// n - 1 times multiply the matrix to {{1,0},{0,1}}
for (i = 2; i <= n; i++)
multiply(F, M);
}
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
static class Pair implements Comparable<Pair>{
int x,y;
Pair(int xx,int yy){
x=xx;y=yy;
}
@Override
public int compareTo(Pair o) {
if(Integer.compare(o.y, this.y)==0){
return Integer.compare(this.x, o.x);
}
else{
return Integer.compare(this.y, o.y);
}
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String readLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* @author ramilagger
*/
public class Main {
final static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
static long f(long a[]) {
int size = a.length;
long max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++) {
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
void solve() {
int n = nextInt();
int[] a = nextArray(n);
long aa[] = new long[n];
long bb[] = new long[n];
Arrays.fill(aa,Long.MIN_VALUE / 10);
Arrays.fill(bb,Long.MIN_VALUE / 10);
int c = 1;
for (int i = 0; i < n - 1; i++) {
aa[i] = Math.abs(a[i] - a[i + 1]) * c;
c = -c;
}
c = 1;
for (int i = 1; i < n - 1; i++) {
bb[i - 1] = Math.abs(a[i] - a[i + 1]) * c;
c = -c;
}
pw.println(Math.max(f(aa),f(bb)));
}
public static void main(String[] args) {
new Main();
}
void run() throws IOException {
start = System.currentTimeMillis();
solve();
if (!ONLINE_JUDGE)
System.err.println(System.currentTimeMillis() - start + " ms");
br.close();
pw.close();
}
Main() {
try {
br = (ONLINE_JUDGE) ? new BufferedReader(new InputStreamReader(System.in))
: new BufferedReader(new FileReader("in.txt"));
pw = (ONLINE_JUDGE) ? new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
: new PrintWriter(new BufferedWriter(new FileWriter("out.txt")));
this.run();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
boolean hasNext() {
if (st != null && st.hasMoreTokens())
return true;
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return false;
}
return true;
}
String next() {
if (hasNext())
return st.nextToken();
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
BigInteger nextBigInteger() {
return new BigInteger(next());
}
String nextLine() {
StringBuilder sb;
try {
while (st == null || !st.hasMoreTokens()) return br.readLine();
sb = new StringBuilder(st.nextToken());
while (st.hasMoreTokens()) sb.append(" " + st.nextToken());
} catch (IOException e) {
throw new RuntimeException();
}
return sb.toString();
}
int[] nextArray(int n) {
int[] temp = new int[n];
for (int i = 0; i < n; i++)
temp[i] = nextInt();
return temp;
}
long[] nextLArray(int n) {
long[] temp = new long[n];
for (int i = 0; i < n; i++)
temp[i] = nextLong();
return temp;
}
long start;
final BufferedReader br;
final PrintWriter pw;
StringTokenizer st;
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void uin(T &a, T b) {
if (b < a) {
a = b;
}
}
template <typename T>
void uax(T &a, T b) {
if (b > a) {
a = b;
}
}
const long long maxn = 100 * 1000 + 228;
long long n;
long long a[maxn], b[maxn], pref[maxn];
void solve() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (long long i = 1; i <= (long long)n; ++i) {
cin >> b[i];
}
for (long long i = 1; i <= (long long)n - 1; ++i) {
a[i] = abs(b[i] - b[i + 1]);
long long kek = 1;
if (i % 2 == 0) {
kek = -1;
}
pref[i] = pref[i - 1] + a[i] * kek;
}
long long mn_odd = 0, mn_even = 0, mn_odd1 = 0, mn_even1 = 0;
long long res = 0;
for (long long i = 1; i <= (long long)n - 1; ++i) {
if (i & 1) {
uax(res, pref[i] - mn_even);
uax(res, -pref[i] - mn_odd1);
uin(mn_odd1, -pref[i]);
uin(mn_odd, pref[i]);
} else {
uax(res, pref[i] - mn_even);
uax(res, -pref[i] - mn_odd1);
uin(mn_even1, -pref[i]);
uin(mn_even, pref[i]);
}
}
cout << res << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
solve();
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long f(int *temp, int n) {
long long ans = 0, cur = 0;
for (int i = 0; i < n - 1; i++) {
cur += temp[i];
if (cur < 0) {
cur = 0;
}
ans = max(ans, cur);
}
return ans;
}
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int temp[n], temp1[n], m = 1;
for (int i = 0; i < n - 1; i++) {
temp[i] = abs(arr[i] - arr[i + 1]) * m;
temp1[i] = -1 * temp[i];
m *= -1;
}
long long ans = f(temp, n);
ans = max(ans, f(temp1, n));
cout << ans << endl;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int a[];
static long dp[][];
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader;
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(bufferedReader.readLine());
a = new int[N];
dp = new long[2][N];
String[] temp;
temp = bufferedReader.readLine().split(" ");
for (int i = 0; i < N; i++)
a[i] = Integer.parseInt(temp[i]);
// solveBrute();
System.out.println(solve());
// int c=0;
// System.out.println(c);
}
private static long solveBrute(){
long max=0;
int left=0;
int right=0;
int N=a.length;
for(int l=0;l<N-2;l++){
for(int r=1;r<N-1;r++){
long count=0;
for(int i=l;i<r;i++){
count+= Math.abs(a[i]-a[i+1]) *Math.pow(-1,i-l);
}
if(count> max){
max=count;
left=l;
right =r;
}
}
}
// System.out.println(left+" "+right+" "+max);
return max;
}
private static long solve() {
int N=a.length;
dp[0][N-1]=0;
dp[1][N-1]=0;
for(int i=N-2;i>=0;i--){
dp[0][i]=Math.abs(a[i]-a[i+1]);
if(i%2==0)
dp[1][i]=dp[0][i]-Math.max(dp[0][i+1],dp[1][i+1]);
else
dp[1][i]=dp[0][i]-Math.min(dp[0][i+1],dp[1][i+1]);
}
long count=0;
for(int i=0;i<N-1;i++){
if(dp[0][i]>count)
count=dp[0][i];
if(dp[1][i]>count)
count=dp[1][i];
}
dp[0][N-1]=0;
dp[1][N-1]=0;
for(int i=N-2;i>=0;i--){
dp[0][i]=Math.abs(a[i]-a[i+1]);
if(i%2==0)
dp[1][i]=dp[0][i]-Math.min(dp[0][i+1],dp[1][i+1]);
else
dp[1][i]=dp[0][i]-Math.max(dp[0][i+1],dp[1][i+1]);
}
long count2=0;
for(int i=0;i<N-1;i++){
if(dp[0][i]>count)
count2=dp[0][i];
if(dp[1][i]>count2)
count2=dp[1][i];
}
return Math.max(count,count2);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int n;
long long a[100100];
long long b[100100];
long long c[100100];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i < n; i++) {
b[i] = abs(a[i] - a[i + 1]);
c[i] = abs(a[i] - a[i + 1]);
}
for (int i = 1; i < n; i++) {
if (i % 2 == 1) b[i] *= -1;
if (i % 2 == 0) c[i] *= -1;
}
long long cnt = 0;
long long ans = 0;
for (int i = 1; i < n; i++) {
cnt += b[i];
ans = max(cnt, ans);
cnt = max(0 * 1ll, cnt);
}
cnt = 0;
for (int i = 1; i < n; i++) {
cnt += c[i];
ans = max(cnt, ans);
cnt = max(0 * 1ll, cnt);
}
cout << ans;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
public final class round_407_c
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static int n;
public static void main(String args[]) throws Exception
{
n=sc.nextInt(); long[] a=new long[n+1];
for(int i=1;i<=n;i++)
{
a[i]=sc.nextLong();
}
long[][] pre=new long[2][n+1];int x=1;long sum=0,max=Long.MIN_VALUE,min=0;
for(int i=2;i<=n;i++)
{
long curr=Math.abs(a[i]-a[i-1])*x;sum+=curr;
x*=-1;
max=Math.max(max,sum-min);min=Math.min(min,sum);
}
sum=0;x=1;min=0;
for(int i=3;i<=n;i++)
{
long curr=Math.abs(a[i]-a[i-1])*x;sum+=curr;
pre[1][i]=sum;x*=-1; max=Math.max(max,sum-min);min=Math.min(min,sum);
}
out.println(max);out.close();
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
/*
.
.
.
.
.
.
.
some constants
.
*/
/*
.
.
.
if any
.
.
*/
public static void main(String[] args) throws IOException{
/*
.
.
.
.
.
.
*/
int n=ni();
long arr[]=nla(n);
long sum[]=new long[n-1];
int i,j;
for(i=0;i<n-1;i++){
sum[i]=Math.abs(arr[i]-arr[i+1]);
if(i%2==1){
sum[i]*=-1;
}
}
long ans=Long.MIN_VALUE;
long temp=0;
for(i=0;i<n-1;i++){
temp = Math.max(sum[i],temp+sum[i]);
ans=Math.max(ans,temp);
}
for(i=0;i<n-1;i++){
sum[i] *= -1;
}
temp=0;
for(i=0;i<n-1;i++){
temp=Math.max(sum[i],temp+sum[i]);
ans=Math.max(ans,temp);
}
sop(ans);
/*
.
.
.
.
.
.
.
*/
}
/*
temporary functions
.
.
*/
/*
fuctions
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
abcdefghijklmnopqrstuvwxyz
.
.
.
.
.
.
*/
static int modulo(int j,int m){
if(j<0)
return m+j;
if(j>=m)
return j-m;
return j;
}
static final int mod=1000000007;
static final double eps=1e-8;
static final long inf=100000000000000000L;
static final boolean debug=true;
static Reader in=new Reader();
static StringBuilder ans=new StringBuilder();
static long powm(long a,long b,long m){
long an=1;
long c=a;
while(b>0){
if(b%2==1)
an=(an*c)%m;
c=(c*c)%m;
b>>=1;
}
return an;
}
static Random rn=new Random();
static void sop(Object a){System.out.println(a);}
static int ni(){return in.nextInt();}
static int[] nia(int n){int a[]=new int[n];for(int i=0;i<n;i++)a[i]=ni();return a;}
static long nl(){return in.nextLong();}
static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;}
static String ns(){return in.next();}
static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;}
static double nd(){return in.nextDouble();}
static double[] nda(int n){double a[]=new double[n];for(int i=0;i<n;i++)a[i]=nd();return a;}
static class Reader{
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader(){
reader=new BufferedReader(new InputStreamReader(System.in),32768);
tokenizer=null;
}
public String next(){
while(tokenizer==null || !tokenizer.hasMoreTokens()){
try{
tokenizer=new StringTokenizer(reader.readLine());
}
catch(IOException e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | # Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
def kadane(arr):
maxsofar=-float('inf')
mx=0
for i in arr:
mx+=i
maxsofar=max(maxsofar,mx)
if mx<0:
mx=0
return maxsofar
def main():
n=int(input())
arr=list(map(int,input().split()))
z=[0]*(n-1)
zz=[0]*(n-1)
for i in range(n-1):
z[i]=abs(arr[i]-arr[i+1])*((-1) if i%2 else 1)
zz[i]=-z[i]
print(max(kadane(z),kadane(zz)))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main() | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n=int(input())
a=list(map(int,input().split()))
ans=-10**9-1
mini=0
temp=0
for i in range(n-1):
if(i%2==0):temp+=abs(a[i]-a[i+1])
else:temp-=abs(a[i]-a[i+1])
mini=min(mini,temp)
ans=max(ans,temp-mini)
mini=0
temp=0
for i in range(1,n-1):
if(i%2==0):temp-=abs(a[i]-a[i+1])
else:temp+=abs(a[i]-a[i+1])
mini=min(mini,temp)
ans=max(ans,temp-mini)
print(ans) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
long long int N, ref, temp, maxAns = -1;
const int max_size = 100005;
array<array<long long int, 2>, max_size> dp;
vector<long long int> diffs;
cin >> N >> ref;
for (int i = 0; i < N - 1; ++i) {
cin >> temp;
diffs.push_back(abs(temp - ref));
ref = temp;
}
dp[0][0] = diffs[0];
maxAns = diffs[0];
for (int i = 1; i < N - 1; ++i) {
if (i % 2) {
dp[i][0] = max(dp[i - 1][0] - diffs[i], (long long int)0);
dp[i][1] = dp[i - 1][1] + diffs[i];
} else {
dp[i][0] = dp[i - 1][0] + diffs[i];
dp[i][1] = max(dp[i - 1][1] - diffs[i], (long long int)0);
}
maxAns = max(maxAns, max(dp[i][0], dp[i][1]));
}
cout << maxAns << "\n";
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
long[] is = new long[n];
for (int i = 0; i < n; i++) {
is[i] = in.nextLong();
}
long ans = getAns(is);
long ans2 = getAns(Arrays.copyOfRange(is, 1, n));
// $.debug(ans, ans2);
out.println(Math.max(ans, ans2));
}
private long getAns(long[] is) {
int n = is.length;
if (n < 2) return 0;
long pre = 0;
long res = 0;
long min = 0;
long minPre = 0;
for (int i = 0; i + 1 < n; i += 2) {
// $.debug(i, pre, res, min, minPre);
pre += Math.abs(is[i] - is[i + 1]);
res = Math.max(res, pre - min);
if (i + 2 < n) {
pre -= Math.abs(is[i + 1] - is[i + 2]);
minPre += Math.abs(is[i] - is[i + 1]) - Math.abs(is[i + 1] - is[i + 2]);
min = Math.min(min, minPre);
}
}
// $.debug(pre, res, min, minPre);
return res;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in), 32768);
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
public boolean hasNext() {
while (st == null || !st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
public String next() {
hasNext();
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(raw_input())
a = map(int, raw_input().split())
b = []
for i in range(n - 1):
b += [abs(a[i] - a[i + 1])]
if i % 2:
b[-1] = -b[-1]
def calc(a, n):
sum = 0
res = 0
for i in range(n):
sum = max(0, sum + a[i])
res = max(res, sum)
return res
res = calc(b, n - 1)
b = map(lambda x: -x, b)
res = max(res, calc(b, n - 1))
print res
| PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
public class Main {
private static final long INF = (long)1e16;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextLong();
if (i != 0) a[i - 1] = Math.abs(a[i - 1] - a[i]);
}
--n;
long ans = -INF, sum = 0, sum2 = 0;
int mul = 1;
for (int i = 0; i < n; ++i, mul = -mul) {
sum = Math.max(0, sum + mul * a[i]);
sum2 = Math.max(0, sum2 + -mul * a[i]);
ans = Math.max(Math.max(ans, sum), sum2);
}
System.out.println(ans);
in.close();
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(raw_input())
data = map(int, raw_input().split())
def solve(data):
cur = 0
smallest = 0
ret = abs(data[1] - data[0])
for i in xrange(len(data) - 1):
v = abs(data[i] - data[i + 1])
if i % 2 == 0:
cur += v
else:
cur -= v
ret = max(ret, cur - smallest)
smallest = min(cur, smallest)
return ret
ans = solve(data)
if n > 2:
data = data[1:]
ans = max(ans, solve(data))
print ans | PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.Scanner;
public class A788 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] A = new int[N];
for (int n=0; n<N; n++) {
A[n] = in.nextInt();
}
long max = 0;
for (int offset=0; offset<2; offset++) {
long sum = 0;
for (int n=0; n<N-offset-1; n++) {
long diff = Math.abs(A[n+1+offset]-A[n+offset]);
if (n%2 == 0) {
sum += diff;
} else {
sum -= diff;
}
if (sum < 0) {
sum = 0;
}
if (sum > max) {
max = sum;
}
}
}
System.out.println(max);
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #!/usr/bin/env python3
from sys import stdin,stdout
def ri():
return map(int, input().split())
n = int(input())
a = list(ri())
b = [abs(a[i]-a[i+1])*(-1)**i for i in range(n-1)]
ans = 0
s = 0
i = 0
while (i < n-1):
s += b[i]
if s < 0:
s = 0
if i%2 == 0:
i += 1
i += 1
ans = max(s, ans)
b = [-b[i] for i in range(n-1)]
s = 0
i = 1
while (i < n-1):
s += b[i]
if s < 0:
s = 0
if i%2 == 1:
i += 1
i += 1
ans = max(s, ans)
print(ans)
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | //I AM THE CREED
/* //I AM THE CREED
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
import java.awt.Point;
public class Main{
//a.push_back
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
while(input.hasNext()){
int n=input.nextInt();
long[] a=new long[n];
long max=0;
long min=0;
for(int i=0;i<n;i++){
a[i]=input.nextLong();
}
long sol=0;
for(int i=n-1;i>=0;i--){
if(i==n-1){
max=0;
min=0;
continue;
}
long prev_max=max;
long prev_min=min;
max=Math.max(Math.abs(a[i]-a[i+1])-prev_min, Math.abs(a[i]-a[i+1]));
min=Math.min(Math.abs(a[i]-a[i+1])-prev_max, 0);
sol=Math.max(sol, max);
}
System.out.println(sol);
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
public class main {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int intLength = input.nextInt();
int[] arrNum = new int[intLength];
long answerImpar = 0;
long sumaImpar = 0;
long answerPar = 0;
long sumaPar = 0;
boolean par = false;
for (int i = 0; i<intLength; i++){
arrNum[i] = input.nextInt();
}
for ( int i = 0 ; i < intLength - 1; i++){
//Math.pow(-1, i + 1) == x * 1 if i = par
par = i%2 != 1;
//Multiplicar por -1 y por 1
answerImpar+= (par) ? -Math.abs(arrNum[i] - arrNum[i + 1]) : Math.abs(arrNum[i] - arrNum[i + 1]);
answerPar+= (par) ? Math.abs(arrNum[i] - arrNum[i + 1]) : -Math.abs(arrNum[i] - arrNum[i + 1]);
sumaImpar = Math.max(answerImpar, sumaImpar);
sumaPar = Math.max(answerPar, sumaPar);
if(answerImpar < 0){
answerImpar = 0;
}
if(answerPar < 0){
answerPar = 0;
}
}
System.out.println(Math.max(sumaImpar, sumaPar));
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(raw_input())
array = [int(x) for x in raw_input().split()]
da = []
for i in xrange(1,n):
da.append(abs(array[i] - array[i-1]))
mejor = 0
tope = [0,0]
for i in xrange(n-1):
tope[i % 2] += da[i]
tope[(i+1)%2] -= da[i]
if tope[(i+1)%2] < 0:
tope[(i+1)%2] = 0
if tope[i % 2] > mejor:
mejor = tope[i % 2]
print mejor
| PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
long long a[100010];
long long dpa[100010];
long long dpb[100010];
long long iabs(long long x) {
if (x < 0) return -x;
return x;
}
int main() {
int n;
scanf("%d", &n);
scanf("%lld", &a[1]);
dpa[1] = 0;
dpb[1] = 0;
long long fuck;
for (int i = 2; i <= n; i++) {
scanf("%lld", &a[i]);
fuck = iabs(a[i] - a[i - 1]);
if (dpa[i - 1] > 0) {
if (i % 2 == 0) {
dpa[i] = dpa[i - 1] - fuck;
} else {
dpa[i] = dpa[i - 1] + fuck;
}
} else {
if (i % 2 == 0) {
dpa[i] = dpa[i] - fuck;
} else {
dpa[i] = fuck;
}
}
if (dpb[i - 1] > 0) {
if (i % 2 == 0) {
dpb[i] = dpb[i - 1] + fuck;
} else {
dpb[i] = dpb[i - 1] - fuck;
}
} else {
if (i % 2 == 0) {
dpb[i] = fuck;
} else {
dpb[i] = dpb[i - 1] - fuck;
}
}
}
long long res = -2e10;
for (int i = 2; i <= n; i++) {
if (dpa[i] > res) res = dpa[i];
if (dpb[i] > res) res = dpb[i];
}
printf("%lld\n", res);
scanf("%d", &n);
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 100009;
const long long INF = 1e16;
int n, a[N];
long long s1[N], s2[N];
long long vout = -INF, t1[2], t2[2];
inline int read() {
char c = getchar();
int f = 1, ret = 0;
while (c < '0' || c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while (c <= '9' && c >= '0') {
ret = ret * 10 + c - '0';
c = getchar();
}
return ret * f;
}
int main() {
n = read();
t1[1] = t2[1] = INF;
for (int i = 1; i <= n; i++) a[i] = read();
for (int i = 1; i < n; i++)
s1[i] = abs(a[i] - a[i + 1]) * (((i - 1) & 1) ? -1 : 1);
for (int i = 1; i < n; i++) s2[i] = abs(a[i] - a[i + 1]) * ((i & 1) ? -1 : 1);
for (int i = 1; i < n; i++) s1[i] += s1[i - 1], s2[i] += s2[i - 1];
for (int i = 1, t; t = (i & 1), i < n; i++) {
vout = max(vout, (i & 1) ? s1[i] - t1[t ^ 1] : s2[i] - t2[t ^ 1]);
vout = max(vout, (i & 1) ? s2[i] - t2[t] : s1[i] - t1[t]);
t1[t] = min(t1[t], s1[i]);
t2[t] = min(t2[t], s2[i]);
}
printf("%lld\n", vout);
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(input())
lis = list(map(int,input().split()))
ab = [abs(lis[i]-lis[i-1]) for i in range(1,n)]
ev=od=ans=0
for i in range(n-1):
if i%2==0:
ev+=ab[i]
od=max(0,od-ab[i])
else:
ev=max(0,ev-ab[i])
od+=ab[i]
ans=max(ans,ev,od)
print(ans)
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
import java.io.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class TestClass {
public static void main(String args[] ) throws Exception {
//Scanner hb=new Scanner(System.in);
InputReader hb=new InputReader(System.in);
PrintWriter w=new PrintWriter(System.out);
int n=hb.nextInt();
int a[]=new int[n];
long f[]=new long[n-1];
for(int i=0;i<n;i++)
{
a[i]=hb.nextInt();
}
for(int i=0;i<n-1;i++)
{
f[i]=Math.abs(a[i]-a[i+1]);
}
long max=Integer.MIN_VALUE;
long ans=0;
for(int i=0;i<n-1;i++)
{
if(i%2==0)
ans+=f[i];
else
ans-=f[i];
max=Math.max(max,ans);
if(ans<0)
ans=0;
}
ans=0;
for(int i=1;i<n-1;i++)
{
if(i%2==1)
ans+=f[i];
else
ans-=f[i];
max=Math.max(max,ans);
if(ans<0)
ans=0;
}
System.out.println(max);
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.Scanner;
import java.io.PrintWriter;
/*
* Examples
input
5
1 4 2 3 1
output
3
input
4
1 5 4 7
output
6
*/
public class P789C_Functions_again {
private static PrintWriter pw;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
pw = new PrintWriter(System.out);
int i, n = in.nextInt() - 1;
long[] diffList = new long[n];
long num = in.nextLong();
long answer = Long.MIN_VALUE;
for (i = 0; i < n; i++) {
long nextNum = in.nextLong();
diffList[i] = Math.abs(num - nextNum);
num = nextNum;
}
num = 0;
for (i = 0; i < n; i++) {
if (num < 0) {
num = 0;
}
num += diffList[i] * (1 - (i & 1) * 2);
if (answer < num) {
answer = num;
}
}
num = 0;
for (i = 1; i < n; i++) {
if (num < 0) {
num = 0;
}
num += diffList[i] * ((i & 1) * 2 - 1);
if (answer < num) {
answer = num;
}
}
pw.printf("%d\n", answer);
in.close();
pw.close();
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int n;
long long kadane(vector<long long> a) {
long long ans = a[0];
long long sum = a[0];
for (int i = 1; i <= n - 2; ++i) {
if (sum < 0) {
sum = a[i];
} else
sum += a[i];
ans = max(ans, sum);
}
return ans;
}
int main() {
cin >> n;
long long arr[n];
vector<long long> a;
vector<long long> b;
for (int i = 0; i < n; ++i) cin >> arr[i];
for (int i = 1; i <= n - 1; ++i) {
long long num = abs(arr[i] - arr[i - 1]);
a.push_back(num), b.push_back(num);
}
for (int i = 0; i < n - 1; i += 2) a[i] = -a[i];
for (int i = 1; i < n - 1; i += 2) b[i] = -b[i];
cout << max(kadane(a), kadane(b));
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
public class CF789C {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine()) - 1;
StringTokenizer st = new StringTokenizer(br.readLine());
int[] aa = new int[n];
int a = Integer.parseInt(st.nextToken());
for (int i = 0; i < n; i++) {
int b = Integer.parseInt(st.nextToken());
aa[i] = Math.abs(a - b);
a = b;
}
if (n == 1) {
System.out.println(aa[0]);
return;
}
long a2 = aa[0], a1 = aa[1], max = Math.max(a1, a2);
for (int i = 2; i < n; i++) {
long tmp = a1; a1 = Math.max(a2 - aa[i - 1] + aa[i], aa[i]); a2 = tmp;
max = Math.max(max, a1);
}
System.out.println(max);
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
long long a[n + 1];
for (long long i = 1; i <= n; i++) cin >> a[i];
long long b[n];
for (long long i = 1; i < n; i++) b[i] = abs(a[i] - a[i + 1]);
long long mx[n + 1], mn[n + 1];
mx[n] = 0;
mn[n] = 0;
long long ans = LLONG_MIN;
for (long long i = n - 1; i >= 1; i--) {
mx[i] = b[i] - mn[i + 1];
mn[i] = b[i] - mx[i + 1];
mx[i] = max(mx[i], b[i]);
ans = max(ans, mx[i]);
}
cout << ans << endl;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1E5 + 10;
int n, A[maxn];
long long Ans, Min, B[maxn];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) scanf("%d", &A[i]);
for (int i = 1; i < n; i++) A[i] = abs(A[i + 1] - A[i]);
for (int i = 1; i < n; i++) B[i] = (i & 1) ? A[i] : -A[i], B[i] += B[i - 1];
for (int i = 1; i < n; i++)
if (i & 1)
Ans = ((Ans) > (B[i] - Min) ? (Ans) : (B[i] - Min));
else
Min = ((Min) < (B[i]) ? (Min) : (B[i]));
Min = 0;
for (int i = 1; i < n; i++) B[i] = (i & 1) ? -A[i] : A[i], B[i] += B[i - 1];
for (int i = 1; i < n; i++)
if (i & 1)
Min = ((Min) < (B[i]) ? (Min) : (B[i]));
else
Ans = ((Ans) > (B[i] - Min) ? (Ans) : (B[i] - Min));
cout << Ans << endl;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
/**
* Created by apple on 2017/1/18.
*/
public class Main {
private Scanner in;
public static void main(String[] args) {
new Main().run();
}
long[] a;
long best[][];
private void run() {
in = new Scanner(System.in);
int n = in.nextInt();
a = new long[n];
best = new long[n][2];
for (int i = 0; i < n; i++) {
a[i] = in.nextLong();
}
best[n - 2][0] = abs(a[n - 2] - a[n - 1]);
best[n - 2][1] = -best[n - 2][0];
long ans = Math.max(best[n - 2][0], best[n - 2][1]);
for (int i = n - 3; i >= 0; i--) {
long t = abs(a[i] - a[i + 1]);
best[i][0] = Math.max(t, t + best[i + 1][1]);
best[i][1] = Math.max(-t, -t + best[i + 1][0]);
t = Math.max(best[i][0], best[i][1]);
if (t > ans) {
ans = t;
}
}
System.out.println(ans);
in.close();
}
private long abs(long x) {
if (x < 0) {
return -x;
}
return x;
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author revanth
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
AFunctionsAgain solver = new AFunctionsAgain();
solver.solve(1, in, out);
out.close();
}
static class AFunctionsAgain {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = new int[n - 1];
for (int i = 1; i < n; i++)
b[i - 1] = Math.abs(a[i] - a[i - 1]);
long max = 0, ans = 0;
for (int i = 0; i < n - 1; i++) {
if (i % 2 == 1)
b[i] *= -1;
max = Math.max(b[i], max + b[i]);
ans = Math.max(max, ans);
}
max = 0;
for (int i = 0; i < n - 1; i++) {
b[i] *= -1;
max = Math.max(b[i], max + b[i]);
ans = Math.max(max, ans);
}
out.println(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class C789 {
public static void main(String[] args) {
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
final long start = System.currentTimeMillis();
new Task1().solve(in, out);
@SuppressWarnings("unused")
final long duration = System.currentTimeMillis()-start;
out.close();
}
static class Task1{
static final int MOD = 1000000007;
static final int MAX = 100001;
ArrayList<Integer> primes;
boolean isPrime[];
public void solve(InputReader in, PrintWriter out){
int n = in.nextInt(), pro = 1;
long[] aa = new long[n];
long[] a = new long[n-1];
for(int i=0; i<n; i++){
aa[i] = in.nextLong();
if(i>0){
a[i-1] = pro*Math.abs(aa[i]-aa[i-1]);
pro = -1*pro;
}
}
long curr = 0, max1 = 0, max2 = 0;
for(int i=0; i<n-1; i++){
curr += a[i];
if(curr<0){
curr = 0;
}
max1 = Math.max(curr, max1);
}
curr = 0;
for(int i=1; i<n-1; i++){
curr -= a[i];
if(curr<0){
curr = 0;
}
max2 = Math.max(curr, max2);
}
out.println(Math.max(max1, max2));
}
void sieve(){
isPrime = new boolean[MAX];
primes = new ArrayList<Integer>();
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
primes.add(2);
for(int i=4; i<MAX; i+=2)
isPrime[i] = false;
for(int i=3; i<MAX; i+=2){
if(isPrime[i]){
primes.add(i);
for(int j=i+i; j<MAX; j+=i)
isPrime[j] = false;
}
}
}
long expo(long a, long b){
long result = 1;
while(b>0){
if(b%2==1) result *= a;
b = b>>1;
a *= a;
}
return result;
}
long fibonacci(long n){
if(n==0) return 0;
long a=0, b=1, c=1, d=1, e=n-2;
long a1, b1, c1, d1, a2=0, b2=1, c2=1, d2=1;
while(e>0){
if(e%2==1){
a1 = (a*a2+b*c2)%MOD;
c1 = (c*a2+d*c2)%MOD;
b1 = (a*b2+ b*d2)%MOD;
d1 = (b2*c+ d*d2)%MOD;
a=a1; b=b1; c=c1; d= d1;
}
a1 = (a2*a2+b2*c2)%MOD;
c1 = (c2*a2+d2*c2)%MOD;
b1 = (a2*b2+ b2*d2)%MOD;
d1 = (b2*c2+ d2*d2)%MOD;
a2=a1; b2=b1; c2=c1; d2= d1;
e /= 2;
}
return d;
}
}
static class InputReader{
final InputStream stream;
final byte[] buf = new byte[8192];
int curChar, numChars;
SpaceCharFilter filter;
public InputReader(){
this.stream = System.in;
}
public int read(){
if(numChars == -1){
throw new InputMismatchException();
}
if(curChar >= numChars){
curChar = 0;
try{
numChars = stream.read(buf);
} catch(IOException e){
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt(){
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-'){
sgn = -1;
c = read();
}
int res = 0;
do{
if(c<'0' || c>'9'){
System.out.println("beta");
throw new InputMismatchException();}
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res*sgn;
}
public long nextLong(){
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-'){
sgn = -1;
c = read();
}
long res = 0;
do{
if(c<'0' || c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res*sgn;
}
public String next(){
int c = read();
while(isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c){
if(filter != null)
return filter.isSpaceChar(c);
return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.*;
public class main {
static ArrayList<Integer> prime;
static boolean check[];
static ArrayList<Integer> queue;
public static void main(String[] args) {
InputReader sc=new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t=1;
while(t-->0){
int n=sc.nextInt();
long a[]=sc.nextIntArray(n);
long sum[]=new long[n-1];
for(int i=0;i<n-1;i++){
sum[i]=Math.abs(a[i]-a[i+1]);
}
long ans=Integer.MIN_VALUE;
int start=0;
long temp=0;
for(int i=0;i<n-1;i++){
if(i%2==0)
temp=temp+sum[i];
else
temp=temp-sum[i];
if(temp>ans)
ans=temp;
if(temp<0){
start=start+2;
temp=0;
}
}
temp=0;
start=1;
for(int i=1;i<n-1;i++){
if(i%2==1)
temp=temp+sum[i];
else
temp=temp-sum[i];
if(temp>ans)
ans=temp;
if(temp<0){
start=start+2;
temp=0;
}
}
System.out.println(ans);
}
pw.close();
}
static int maxSubArraySum(int a[])
{
int size = a.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
static int gcd(int n1,int n2){
int r;
while(n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
private static void printMatrixInSpiralWay(int[][] matrix){
int rowStart=0;
int rowLength=matrix.length-1;
int colStart=0;
int colLength = matrix[0].length-1;
while(rowStart <= rowLength && colStart <= colLength){
for (int i = rowStart; i <= colLength; i++) {
System.out.print(matrix[rowStart][i] + " ");
}
for (int j = rowStart+1; j <= rowLength; j++) {
System.out.print(matrix[j][colLength] + " ");
}
if(rowStart+1 <= rowLength){
for (int k = colLength-1; k >= colStart; k--) {
System.out.print(matrix[rowLength][k] + " ");
}
}
if(colStart+1 <= colLength){
for (int k = rowLength-1; k > rowStart; k--) {
System.out.print(matrix[k][colStart] + " ");
}
}
rowStart++;
rowLength--;
colStart++;
colLength--;
}
}
public static long fact(int n){
long ans=1;
for(long i=2;i<=n;i++){
ans=(ans*i)%1000000007;
}
return ans;
}
public static int pop(){
int x=queue.get(0);
queue.remove(0);
return x;
}
public static int[][] sort2D(int arr[][]){
Arrays.sort(arr, new Comparator<int[]>()
{
public int compare(int[] o1, int[] o2)
{
return(Integer.compare(o2[0],o1[0]));
}
});
return arr;
}
public class Pair {
private final int x;
private final int y;
public Pair(final int x, final int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Pair)) {
return false;
}
final Pair pair = (Pair) o;
if (x != pair.x) {
return false;
}
if (y != pair.y) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long[] nextIntArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = (long)nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import sys, math
from sys import stdin, stdout
from collections import deque
from copy import deepcopy
rem = 10 ** 9 + 7
sys.setrecursionlimit(10 ** 6)
take = lambda: map(int, raw_input().split())
from sys import maxint
def maxSubArraySum(a, size):
max_so_far = -maxint - 1
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
n=input()
arr=take()
new=[]
fun=[]
for i in range(n-1):
if i%2==0:
new.append(abs(arr[i+1]-arr[i]))
fun.append(-abs(arr[i+1]-arr[i]))
else:
new.append(-(abs(arr[i+1]-arr[i])))
fun.append(abs(arr[i+1]-arr[i]))
print max(maxSubArraySum(fun,n-1),maxSubArraySum(new,n-1))
| PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author MaxHeap
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FunctionsAgain solver = new FunctionsAgain();
solver.solve(1, in, out);
out.close();
}
static class FunctionsAgain {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
int[] diff = new int[n - 1];
for (int i = 1; i < n; i++) {
diff[i - 1] = Math.abs(arr[i] - arr[i - 1]);
}
// first
for (int i = 0; i < n - 1; i += 2) {
diff[i] = -diff[i];
}
long ans = (long) -1e18;
long best = (long) -1e18;
for (int i = 0; i < n - 1; i++) {
if (best < 0) {
best = 0;
}
best += diff[i];
ans = Math.max(ans, best);
}
for (int i = 0; i < n - 1; i++) {
diff[i] = -diff[i];
}
best = (long) -1e18;
for (int i = 0; i < n - 1; i++) {
if (best < 0) {
best = 0;
}
best += diff[i];
ans = Math.max(ans, best);
}
out.println(ans);
}
}
static class FastReader {
BufferedReader reader;
StringTokenizer st;
public FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
int i = 0;
while (i < n) {
arr[i++] = nextInt();
}
return arr;
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
long long ans1 = LLONG_MIN, ans2 = LLONG_MIN, mx1 = 0, mx2 = 0;
vector<long long> v(n);
for (int i = 0; i < n; ++i) {
cin >> v[i];
}
for (int i = 1; i < n; ++i) {
if (i % 2 == 0) {
mx1 = max(mx1 - abs(v[i] - v[i - 1]), 0LL);
ans1 = max(ans1, mx1);
mx2 = max(mx2 + abs(v[i] - v[i - 1]), 0LL);
ans2 = max(ans2, mx2);
} else {
mx1 = max(mx1 + abs(v[i] - v[i - 1]), 0LL);
ans1 = max(ans1, mx1);
mx2 = max(mx2 - abs(v[i] - v[i - 1]), 0LL);
ans2 = max(ans2, mx2);
}
}
cout << max(ans1, ans2) << '\n';
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
public class fagain{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] a = new long[n];
for(int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
long[] dif = new long[n-1];
for (int i = 0; i < n-1; i++) {
dif[i] = (long)(Math.abs(a[i]-a[i + 1]));
}
long max = dif[0];
long x = dif[0];
long y = 0;
for (int i = 1; i < n - 1; i++) {
if (i % 2 == 0) {
x += dif[i];
y -= dif[i];
if (y < 0) {
y = 0;
}
if (x > max) {
max = x;
}
}
else {
x -= dif[i];
y += dif[i];
if (x < 0) {
x = 0;
}
if (y > max) {
max = y;
}
}
}
System.out.println(max);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
//http://codeforces.com/problemset/problem/788/A
//maximum sub array
//minimum sub array
//μ§μ νμ λλ μ?
//ν΄λΉ μΉΈμμ μμλ©΄ 0 μμλ©΄ maxμ ν©μΉλ€?
public class Solution788A {
public static int[] arr = new int[100001];
public static int[] dist = new int[100001];
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for(int i = 1; i <= n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
long finalMax = 0;
for(int start = 1; start < 3; start++) {
long max = 0;
long sum = 0;
boolean add = true;
for(int i = start; i < n; i++) {
dist[i] = Math.abs(arr[i] - arr[i+1]);
if(add) {
sum += dist[i];
max = sum > max ? sum : max;
add = false;
}
else {
sum -= dist[i];
add = true;
}
if(sum < 0) {
sum = 0;
add = true;
}
}
finalMax = max > finalMax ? max : finalMax;
}
// for(int i = 1; i <= n-1; i++) {
// System.out.print(dist[i] +" ");
// }
//
//
//
// for(int l = 1, r = 2; r <= n; r++) {
// long currSum = func(l,r);
// max = currSum > max ? currSum : max;
//
// }
//
System.out.println(finalMax);
}
// public static long func(int l, int r) {
// long sum = 0;
// long[] dp = new long[100001];
//
// for(int i = l; i < r; i++) {
// dp[i] = helpFunc(l,i);
//
// sum += dp[i];
// }
//
// return sum;
// }
//
// public static long helpFunc(int l, int i) {
// return(int)(Math.abs(arr[i] - arr[i+1]) * Math.pow(-1,i-l));
// }
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long n, m, f[1000100][2], a[1000100], c[1000100], ans;
inline int getint() {
int w = 0, q = 0;
char c = getchar();
while ((c < '0' || c > '9') && c != '-') c = getchar();
if (c == '-') q = 1, c = getchar();
while (c >= '0' && c <= '9') w = w * 10 + c - '0', c = getchar();
return q ? -w : w;
}
int main() {
cin >> n;
for (long long i = 1; i <= n; i++) c[i] = getint();
for (long long i = 1; i < n; i++) a[i] = abs(c[i + 1] - c[i]);
n--;
for (long long i = 1; i <= n; i++) {
f[i][0] = max((long long)0, f[i - 1][1] - a[i]);
f[i][1] = f[i - 1][0] + a[i];
ans = max(ans, max(f[i][0], f[i][1]));
}
cout << ans;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long a[100005];
long long d[100005];
long long Min[100005];
long long Max[100005];
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n - 1; i++) {
d[i] = abs(a[i + 1] - a[i]);
}
Min[n - 1] = Max[n - 1] = 0;
long long ans = -1000000000;
for (int i = n - 2; i >= 0; i--) {
Min[i] = min(0LL, d[i] - Max[i + 1]);
Max[i] = max(0LL, d[i] - Min[i + 1]);
ans = max(ans, Max[i]);
}
cout << ans << endl;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
}
///////////////////////////////////////////////////////////////////////////////////////////
// RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL //
// RR RRR AAAAA HHH HHH IIIIIIIIIII LLL //
// RR RRR AAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHHHHHHHHHH III LLL //
// RRRRRR AAA AAA HHHHHHHHHHH III LLL //
// RR RRR AAAAAAAAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL //
///////////////////////////////////////////////////////////////////////////////////////////
static int n;
static int arr[];
public static void main(String[] args)throws IOException
{
PrintStream out= new PrintStream(System.out);
Reader sc=new Reader();
n=sc.i();
arr=new int[n];
for(int i=0;i<n;i++)arr[i]=sc.i();
long sum1=0;long sum2=0;long max1=0;long max2=0;
for(int i=0;i<n-1;i++)
{
if(i%2==0)sum1+=(long)Math.abs(arr[i]-arr[i+1]);
else sum1-=(long)Math.abs(arr[i+1]-arr[i]);
max1=Math.max(max1,sum1);
if(sum1<0)sum1=0;
}
for(int i=1;i<n-1;i++)
{
if(i%2==1)sum2+=(long)Math.abs(arr[i]-arr[i+1]);
else sum2-=(long)Math.abs(arr[i+1]-arr[i]);
max2=Math.max(max2,sum2);
if(sum2<0)sum2=0;
}
System.out.println(Math.max(max1,max2));
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | def kadane(A):
if len(A)==0:
return 0
max_c=A[0]
max_g=A[0]
for i in range(1,len(A)):
max_c=max(A[i],max_c+A[i])
if max_c>max_g:
max_g=max_c
return max_g
def answer(n,A):
b=[]
for i in range(0,n-1):
x=abs(A[i]-A[i+1])*(-1)**i
b.append(x)
c=[]
for i in range(1,n-1):
y=abs(A[i]-A[i+1])*((-1)**(i+1))
c.append(y)
s1=kadane(b)
s2=kadane(c)
return max(s1,s2)
n=int(input())
arr=list(map(int,input().split()))
print(answer(n,arr)) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
void solve() {
long long n;
cin >> n;
long long num[n + 1], dif[n];
for (__typeof(n) i = 1; i <= n; i++) {
cin >> num[i];
}
for (__typeof(n - 1) i = 1; i <= n - 1; i++) {
dif[i] = abs(num[i] - num[i + 1]);
if (i % 2) dif[i] = -dif[i];
}
long long maxim = LLONG_MIN, con = 0;
for (__typeof(n - 1) i = 1; i <= n - 1; i++) {
con += dif[i];
maxim = max(maxim, con);
con = con < 0 ? 0 : con;
}
for (__typeof(n - 1) i = 1; i <= n - 1; i++) {
dif[i] = -dif[i];
}
con = 0;
for (__typeof(n - 1) i = 1; i <= n - 1; i++) {
con += dif[i];
maxim = max(maxim, con);
con = con < 0 ? 0 : con;
}
cout << maxim << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int cases = 1;
while (cases--) {
solve();
}
cout << flush;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const double INF = 1e12;
const double eps = 1e-9;
int n;
long long a[N];
long long maxSubArray() {
long long ret = a[0], cur = a[0];
for (int i = 1; i < n - 1; i++) {
cur = max(a[i], cur + a[i]);
ret = max(ret, cur);
}
return ret;
}
int main() {
scanf("%d%lld", &n, a);
for (int i = 0; i < n - 1; i++) {
scanf("%lld", a + i + 1);
a[i] = abs(a[i + 1] - a[i]);
if (i % 2) a[i] = -a[i];
}
long long res1 = maxSubArray();
for (int i = 0; i < n - 1; i++) a[i] = -a[i];
long long res2 = maxSubArray();
printf("%lld", max(res1, res2));
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 |
import java.util.Scanner;
public class con2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long[] a = new long[n-1];
long l = in.nextLong();
for (int i = 1; i < n; i++) {
long c = in.nextLong();
a[i-1] = Math.abs(l - c);
l = c;
}
long max = 0;
long sum = 0;
for (int i = 0; i < n-1; i++) {
if (sum < 0){
sum = 0;
}
if (i%2 == 0){
sum += a[i];
}
else {
sum -= a[i];
}
if (sum > max){
max = sum;
}
}
sum = 0;
for (int i = 0; i < n-1; i++) {
if (sum < 0){
sum = 0;
}
if (i%2 == 1){
sum += a[i];
}
else {
sum -= a[i];
}
if (sum > max) {
max = sum;
}
}
System.out.println(max);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
std::ios_base::sync_with_stdio(false);
int n;
cin >> n;
long long ar[n], d[n];
for (int i = 0; i < n; i++) {
cin >> ar[i];
}
for (int i = 0; i < n - 1; i++) d[i] = abs(ar[i] - ar[i + 1]);
long long ar1[n - 1], ar2[n - 1];
for (int i = 0; i < n - 1; i++) {
ar2[i] = ar1[i] = d[i];
if (i % 2)
ar1[i] *= -1;
else
ar2[i] *= -1;
}
long long ans = 0, mx = 0;
for (int i = 0; i < n - 1; i++) {
mx += ar1[i];
if (mx < 0) mx = 0;
if (mx > ans) ans = mx;
}
mx = 0;
for (int i = 0; i < n - 1; i++) {
mx += ar2[i];
if (mx < 0) mx = 0;
if (mx > ans) ans = mx;
}
cout << ans << endl;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import math
from collections import defaultdict as dd
def main():
n = int(input())
A = list(map(int, input().split()))
# print(A)
B = []
for i in range(1, len(A)):
B.append(abs(A[i]-A[i-1]))
# print(B)
Dp = dd(int)
Dm = dd(int)
Dp[0]=0
MAX = 0
for i in range(n-1):
Dm[i] = Dp[i-1] + B[i]
Dp[i] = max(Dm[i-1] - B[i], 0)
MAX = max(Dm[i], Dp[i], MAX)
print(MAX)
if __name__ == "__main__":
main()
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
static final int INF = (int)2e9;
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = sc.nextInt();
int[] diff = new int[n-1];
for(int i = 0; i < n-1; i++) diff[i] = Math.abs(a[i] - a[i+1]);
out.println(Math.max(kadan(diff, true), kadan(diff, false)));
out.flush();
out.close();
}
static long kadan(int[] a, boolean pos)
{
int max = -INF;
for(int i = 0; i < a.length; i++)
{
if(i % 2 == 1 && pos || i % 2 == 0 && !pos)
a[i] *= -1;
max = Math.max(max, a[i]);
}
if(max < 0) return 1l * max;
long ans = 0, cur = 0;
for(int i = 0; i < a.length; i++)
{
cur += a[i];
ans = Math.max(ans, cur);
cur = Math.max(0, cur);
}
for(int i = 0; i < a.length; i++)
if(i % 2 == 1 && pos || i % 2 == 0 && !pos)
a[i] *= -1;
return ans;
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream System){br = new BufferedReader(new InputStreamReader(System));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine()throws IOException{return br.readLine();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar()throws IOException{return next().charAt(0);}
public Long nextLong()throws IOException{return Long.parseLong(next());}
public boolean ready() throws IOException{return br.ready();}
public void waitForInput(){for(long i = 0; i < 3e9; i++);}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
public class CF_788_A {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;++i)
arr[i]=sc.nextInt();
long diff[]=new long[n-1];
for(int i=1;i<n;++i)
diff[i-1]=Math.abs(arr[i]+0l-arr[i-1])*(i%2==1?-1:1);
long max=0;
long tot=0;
for(int i=0;i<n-1;++i) {
tot+=diff[i];
tot=Math.max(0,tot);
max=Math.max(tot,max);
}
for(int i=0;i<n-1;++i) {
diff[i]*=-1;
}
tot=0;
for(int i=0;i<n-1;++i) {
tot+=diff[i];
tot=Math.max(0,tot);
max=Math.max(tot,max);
}
System.out.println(max);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> v(n - 1);
for (int i = 0; i < n - 1; i++) {
v[i] = abs(a[i] - a[i + 1]);
}
vector<vector<long long>> dp(n + 1, vector<long long>(2));
long long ans = 0;
for (int i = 1; i < n; i++) {
dp[i][1] = max(0ll, dp[i - 1][0]) + v[i - 1];
dp[i][0] = dp[i - 1][1] - v[i - 1];
ans = max(ans, max(dp[i][0], dp[i][1]));
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
solve();
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int n;
int a[110000];
long long b[110000];
long long c[110000];
long long d[110000];
int getZ(int x) {
if (x % 2 == 0)
return 1;
else
return -1;
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
for (int i = 0; i < n - 1; ++i) b[i] = abs(a[i] - a[i + 1]);
long long ans = -(long long)1e15;
long long sum = 0;
long long min_sum = 0;
for (int i = 0; i < n - 1; ++i) {
sum += b[i] * (i % 2 == 0 ? 1 : -1);
ans = max(ans, sum - min_sum);
if (i % 2 == 1) min_sum = min(min_sum, sum);
}
sum = 0;
min_sum = (long long)1e15;
for (int i = 0; i < n - 1; ++i) {
sum += b[i] * (i % 2 == 1 ? 1 : -1);
ans = max(ans, sum - min_sum);
if (i % 2 == 0) min_sum = min(min_sum, sum);
}
cout << ans << "\n";
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
import java.io.*;
public class ProblemA {
public static void main(String[] args) {
// TODO Auto-generated method stub
FastScanner input = new FastScanner();
int n = input.nextInt();
long[] arr = input.readLongArray(n);
long[] arr1 = new long[n-1];
long[] arr2 = new long[n-1];
for(int a = 0; a < n-1; a++){
long val = Math.abs(arr[a]-arr[a+1]);
if(a%2 == 0){
arr1[a] = val;
arr2[a] = -1 * val;
}
else{
arr2[a] = val;
arr1[a] = -1 * val;
}
}
System.out.println(Math.max(maxSubArray(arr1), maxSubArray(arr2)));
}
public static long maxSubArray(long[] A) {
long newsum = A[0];
long max = A[0];
for (int i = 1; i < A.length; i++) {
newsum = Math.max(newsum + A[i], A[i]);
max = Math.max(max, newsum);
}
return max;
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextLong();
}
return a;
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<long long> vec(n + 1);
for (int i = 1; i <= n; i++) cin >> vec[i];
vector<long long> a;
for (int i = 1; i < n; i++) {
if (i & 1)
a.push_back(abs(vec[i] - vec[i + 1]));
else
a.push_back(-1 * abs(vec[i] - vec[i + 1]));
}
vector<long long> dp((int)a.size());
dp[0] = a[0];
long long res = dp[0];
for (int i = 1; i < dp.size(); i++) {
dp[i] = max(a[i], dp[i - 1] + a[i]);
res = max(res, dp[i]);
}
dp.clear();
a.clear();
for (int i = 1; i < n; i++) {
if (!(i & 1))
a.push_back(abs(vec[i] - vec[i + 1]));
else
a.push_back(-1 * abs(vec[i] - vec[i + 1]));
}
dp = vector<long long>((int)a.size());
dp[0] = a[0];
long long res2 = dp[0];
for (int i = 1; i < dp.size(); i++) {
dp[i] = max(a[i], dp[i - 1] + a[i]);
res2 = max(res2, dp[i]);
}
cout << max(res, res2) << '\n';
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int a[100005], b[100005];
int main() {
int n, i;
cin >> n;
for (i = 0; i < n; i++) scanf("%d", a + i);
for (i = 0; i < n - 1; i++) b[i] = abs(a[i] - a[i + 1]);
for (i = 1; i < n - 1; i += 2) b[i] = -b[i];
n--;
long long cur = 0, ans = 0;
for (i = 0; i < n; i++) {
cur = max(0ll, cur + b[i]);
ans = max(ans, cur);
}
for (i = 0; i < n; i++) b[i] = -b[i];
cur = 0;
for (i = 0; i < n; i++) {
cur = max(0ll, cur + b[i]);
ans = max(ans, cur);
}
cout << ans;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = in.nextInt();
}
long[] dp = new long[n];
for(int i = 0; i < n-1; i++){
dp[i] = Math.abs(a[i]-a[i+1]);
}
long res = dp[0];
long pos = dp[0];
long neg = 0;
for(int i = 1; i < n-1; i++){
int s = (i % 2 == 0) ? 1 : -1;
pos += s * dp[i];
neg -= s * dp[i];
if(pos < 0) pos = 0;
if(neg < 0) neg = 0;
res = Math.max(res, pos);
res = Math.max(res, neg);
}
out.println(res);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
long evenAns = 0;
long oddAns = 0;
long[] evenPref = new long[n];
long[] oddPref = new long[n];
int sign = 1;
for (int i = 1; i < n; i++) {
evenPref[i] = evenPref[i - 1] + Math.abs(a[i - 1] - a[i]) * sign;
sign = -sign;
}
sign = 1;
for (int i = 2; i < n; i++) {
oddPref[i] = oddPref[i - 1] + Math.abs(a[i - 1] - a[i]) * sign;
sign = -sign;
}
long minV = 0;
for (int i = 0; i < n; i++) {
evenAns = Math.max(evenAns, evenPref[i] - minV);
minV = Math.min(minV, evenPref[i]);
}
minV = 0;
for (int i = 0; i < n; i++) {
oddAns = Math.max(oddAns, oddPref[i] - minV);
minV = Math.min(minV, oddPref[i]);
}
out.println(Math.max(evenAns, oddAns));
}
}
static class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private void fillTokenizer() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String next() {
fillTokenizer();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 |
import java.util.*;
import java.io.*;
public class Solution {
static FastScanner scr=new FastScanner();
// static Scanner scr=new Scanner(System.in);
static PrintStream out=new PrintStream(System.out);
static StringBuilder sb=new StringBuilder();
static class pair{
int x;int y;
pair(int x,int y){
this.x=x;this.y=y;
}
}
static class triplet{
int x;
long y;
int z;
triplet(int x,long y,int z){
this.x=x;
this.y=y;
this.z=z;
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
} long gcd(long a,long b){
if(b==0) {
return a;
}
return gcd(b,a%b);
}
int[] sort(int a[]) {
int multiplier = 1, len = a.length, max = Integer.MIN_VALUE;
int b[] = new int[len];
int bucket[];
for (int i = 0; i < len; i++) if (max < a[i]) max = a[i];
while (max / multiplier > 0) {
bucket = new int[10];
for (int i = 0; i < len; i++) bucket[(a[i] / multiplier) % 10]++;
for (int i = 1; i < 10; i++) bucket[i] += (bucket[i - 1]);
for (int i = len - 1; i >= 0; i--) b[--bucket[(a[i] / multiplier) % 10]] = a[i];
for (int i = 0; i < len; i++) a[i] = b[i];
multiplier *= 10;
}
return a;
}
long modPow(long base,long exp) {
if(exp==0) {
return 1;
}
if(exp%2==0) {
long res=(modPow(base,exp/2));
return (res*res);
}
return (base*modPow(base,exp-1));
}
int []reverse(int a[]){
int b[]=new int[a.length];
int index=0;
for(int i=a.length-1;i>=0;i--) {
b[index]=a[i];
}
return b;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLongArray(int n) {
long [] a=new long [n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static ArrayList<pair>a;
static int prime[];
static void solve() {
int n=scr.nextInt();
int []a=scr.readArray(n);
int pref[]=new int[n-1];
for(int i=0;i<n-1;i++) {
pref[i]=Math.abs(a[i]-a[i+1]);
if((i%2==0)) {
pref[i]=-pref[i];
}
}
long max=0;
long currMax=pref[0];
for(int i=1;i<n-1;i++) {
currMax=Math.max(pref[i], currMax+pref[i]);
max=Math.max(currMax, max);
}
currMax=-pref[0];
max=Math.max(max, currMax);
for(int i=1;i<n-1;i++) {
currMax=Math.max(-pref[i], currMax-pref[i]);
max=Math.max(currMax, max);
}
out.println(max);
}
static int MAX = Integer.MAX_VALUE;
static int MIN = Integer.MIN_VALUE;
public static void main(String []args) {
// int t=scr.nextInt();
// while(t-->0) {
// solve();
// }
solve();
out.println(sb);
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long tabela[(int)1e5 + 100];
long long dp(vector<long long> &second, long long idx, long long L) {
if (tabela[idx] != -1) return tabela[idx];
if (idx <= L) return tabela[idx] = second[L];
return tabela[idx] = max(second[idx], second[idx] + dp(second, idx - 1, L));
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n;
cin >> n;
vector<long long> v(n);
for (int i = 0; i < (int)(n); i++) {
cin >> v[i];
}
vector<long long> s1(n - 1);
for (long long i = 0; i < n - 1; i++) {
s1[i] = (long long)abs(v[i] - v[i + 1]);
if (i % 2) {
s1[i] *= -1;
}
}
long long maior = (long long)-1e10;
memset(tabela, -1, sizeof(tabela));
for (long long i = 0; i < (long long)s1.size(); i++) {
maior = max(maior, dp(s1, i, 0));
}
for (int i = 0; i < (int)(s1.size()); i++) s1[i] *= -1;
memset(tabela, -1, sizeof(tabela));
for (long long i = 1; i < (long long)s1.size(); i++) {
maior = max(maior, dp(s1, i, 1));
}
cout << maior << "\n";
;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
/*
* Java Input / Output Class using Buffered/ Input Straem
* Created by @neelbhallabos
* File Created at: Mar 25, 2019
*/
public class FunctionAgain {
public static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
public static StringTokenizer st;
public static PrintWriter pw = new PrintWriter(System.out);
final static boolean debugmode = true;
public static int k = 7; // for 10^9 + k mods.
public static long STMOD = 1000000000 + k; // 10^9 + k
public static void main(String[] args) throws IOException {
int npts = getInt();
int prev = getInt();
int[] values = new int[npts-1];
for(int i = 0; i < npts-1;i++) {
int nxt = getInt();
values[i] = Math.abs(nxt-prev);
prev = nxt;
}
if(values.length == 1) {
submit(Math.max(values[0],0),true);
return;
}
// 2 way dp table.
long[] maxat = new long[npts-1];
maxat[0] = values[0];
maxat[1] = values[1];
for(int i = 2; i < values.length;i++) {
int diff = values[i]-values[i-1];
if (diff >= 0) {
maxat[i] = Math.max(values[i], maxat[i-2]+diff);
}
else {
maxat[i] = Math.max(values[i], maxat[i-2]+diff);
}
}
long cmax = maxat[0];
for(long x : maxat) {
cmax = Math.max(cmax, x);
}
submit(cmax,true);
}
public static void setInputFile(String fn) throws IOException {
sc = new BufferedReader(new FileReader(fn));
}
public static void setOutputFile(String fn) throws IOException {
pw = new PrintWriter(new BufferedWriter(new FileWriter(fn)));
}
public static int GCD(int a, int b) {
if (b == 0)
return a;
return GCD(b, a % b);
}
public static double log(int k, int v) {
return Math.log(k) / Math.log(v);
}
public static long longpower(int a, int b) {
long[] vals = new long[(int) (log(b, 2) + 2)];
vals[0] = a;
vals[1] = a * a;
for (int i = 1; i < vals.length; i++) {
vals[i] = vals[i - 1] * vals[i - 1];
}
long ans = 1;
int cindex = 0;
while (b != 0) {
if (b % 2 == 1) {
ans *= vals[cindex];
}
cindex += 1;
b /= 2;
}
return ans;
}
public static void debug(String toPrint) {
if (!debugmode) {
return;
}
pw.println("[DEBUG]: " + toPrint);
}
public static void submit(int[] k, boolean close) {
pw.println(Arrays.toString(k));
if (close) {
pw.close();
}
}
public static void submit(int p, boolean close) {
pw.println(Integer.toString(p));
if (close) {
pw.close();
}
}
public static void submit(String k, boolean close) {
pw.println(k);
if (close) {
pw.close();
}
}
public static void submit(double u, boolean close) {
pw.println(Double.toString(u));
if (close) {
pw.close();
}
}
public static void submit(long lng, boolean close) {
pw.println(Long.toString(lng));
if (close) {
pw.close();
}
}
public static void submit() {
pw.close();
}
public static int getInt() throws IOException {
if (st != null && st.hasMoreTokens()) {
return Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(sc.readLine());
return Integer.parseInt(st.nextToken());
}
public static long getLong() throws IOException {
if (st != null && st.hasMoreTokens()) {
return Long.parseLong(st.nextToken());
}
st = new StringTokenizer(sc.readLine());
return Long.parseLong(st.nextToken());
}
public static double getDouble() throws IOException {
if (st != null && st.hasMoreTokens()) {
return Double.parseDouble(st.nextToken());
}
st = new StringTokenizer(sc.readLine());
return Double.parseDouble(st.nextToken());
}
public static String getString() throws IOException {
if (st != null && st.hasMoreTokens()) {
return st.nextToken();
}
st = new StringTokenizer(sc.readLine());
return st.nextToken();
}
public static String getLine() throws IOException {
return sc.readLine();
}
public static int[][] readMatrix(int lines, int cols) throws IOException {
int[][] matrr = new int[lines][cols];
for (int i = 0; i < lines; i++) {
for (int j = 0; j < cols; j++) {
matrr[i][j] = getInt();
}
}
return matrr;
}
public static int[] readArray(int lines) throws IOException {
int[] ar = new int[lines];
for (int i = 0; i < lines; i++)
ar[i] = getInt();
return ar;
}
}
/*
public class FunctionAgain {
}
*/ | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import sys
import os
from io import BytesIO, IOBase
from collections import Counter, deque
import math
'''import time
import collections
import itertools
import timeit
import random
from bisect import bisect_left as bl
from bisect import bisect_right as br '''
#########################
# imgur.com/Pkt7iIf.png #
#########################
# returns the list of prime numbers less than or equal to n:
'''def sieve(n):
if n < 2: return list()
prime = [True for _ in range(n + 1)]
p = 3
while p * p <= n:
if prime[p]:
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 2
r = [2]
for p in range(3, n + 1, 2):
if prime[p]:
r.append(p)
return r'''
# returns all the divisors of a number n(takes an additional parameter start):
'''def divs(n, start=1):
divisors = []
for i in range(start, int(math.sqrt(n) + 1)):
if n % i == 0:
if n / i == i:
divisors.append(i)
else:
divisors.extend([i, n // i])
return divisors'''
# returns the number of factors of a given number if a primes list is given:
'''def divn(n, primes):
divs_number = 1
for i in primes:
if n == 1:
return divs_number
t = 1
while n % i == 0:
t += 1
n //= i
divs_number *= t
return divs_number'''
# returns the leftmost and rightmost positions of x in a given list d(if x isnot present then returns (-1,-1)):
'''def flin(d, x, default=-1):
left = right = -1
for i in range(len(d)):
if d[i] == x:
if left == -1: left = i
right = i
if left == -1:
return (default, default)
else:
return (left, right)'''
# returns (b**p)%m
'''def modpow(b,p,m):
res=1
b=b%m
while(p):
if p&1:
res=(res*b)%m
b=(b*b)%m
p>>=1
return res'''
# if m is a prime this can be used to determine (1//a)%m or modular multiplicative inverse of a number a
'''def mod_inv(a,m):
return modpow(a,m-2,m)'''
# returns the ncr%m for (if m is a prime number) for very large n and r
'''def ncr(n,r,m):
res=1
if r==0:
return 1
if n-r<r:
r=n-r
p,k=1,1
while(r):
res=((res%m)*(((n%m)*mod_inv(r,m))%m))%m
n-=1
r-=1
return res'''
# returns ncr%m (if m is a prime number and there should be a list fact which stores the factorial values upto n):
'''def ncrlis(n,r,m,fact):
return (fact[n]*(mod_inv(fact[r],m)*mod_inv(fact[n-r],m))%m)%m'''
def ceil(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def prr(a, sep=' '): print(sep.join(map(str, a)))
def dd(): return collections.defaultdict(int)
def ddl(): return collections.defaultdict(list)
def ddd(): return collections.defaultdict(collections.defaultdict(int))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n=ii()
a=li()
if n==2:
print(abs(a[0]-a[1]))
exit()
mx_cur1,mx_glob1=abs(a[0]-a[1]),abs(a[0]-a[1])
for i in range(1,n-1):
tmp=abs(a[i]-a[i+1])*(-1)**i
mx_cur1=max(mx_cur1+tmp,tmp)
mx_glob1=max(mx_cur1,mx_glob1)
mx_cur2,mx_glob2=abs(a[1]-a[2]),abs(a[1]-a[2])
for i in range(2,n-1):
tmp=abs(a[i]-a[i+1])*(-1)**(i-1)
mx_cur2=max(mx_cur2+tmp,tmp)
mx_glob2=max(mx_glob2,mx_cur2)
print(max(mx_glob1,mx_glob2)) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import sys
n = int(input())
a = list(map(int, input().split()))
d = []
for i in range(1,n):
d.append(abs(a[i] - a[i - 1]))
evencur = 0;
sgn = 1;
ans = 0;
for i in range(len(d)):
evencur += d[i] * sgn;
sgn *= -1;
ans = max(evencur, ans)
if evencur < 0:
evencur = 0;
sgn = 1;
evencur = 0;
sgn = 1
for i in range(1,len(d)):
evencur += d[i] * sgn;
sgn *= -1;
ans = max(evencur, ans)
if evencur < 0:
evencur = 0;
sgn = 1;
print(ans)
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int n;
long long a[100005], b[100005];
long long pmax[100005], pmin[100005];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
for (int i = 1; i < n; i++) b[i] = abs(a[i] - a[i + 1]);
for (int i = 2; i < n; i += 2) b[i] *= -1;
for (int i = 1; i <= n; i++) b[i] += b[i - 1];
pmax[n - 1] = pmin[n - 1] = b[n - 1];
for (int i = n - 2; i > 0; i--) {
pmax[i] = max(pmax[i + 1], b[i]);
pmin[i] = min(pmin[i + 1], b[i]);
}
long long ret = -1e18;
for (int i = 1; i < n; i += 2) {
ret = max(ret, pmax[i] - b[i - 1]);
}
for (int i = 2; i < n; i += 2) {
ret = max(ret, b[i - 1] - pmin[i]);
}
cout << ret;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long powmod(long long a, long long l, long long md) {
a %= md;
long long res = 1;
while (l) {
if (l & 1) res = res * a % md;
l /= 2;
a = a * a % md;
}
return res;
}
long long binpow(long long a, long long l) {
long long res = 1;
while (l) {
if (l & 1) res = res * a;
l /= 2;
a = a * a;
}
return res;
}
long long invmod(long long a, long long md) { return powmod(a, md - 2, md); }
long long __set(long long b, long long i) { return b | (1LL << i); }
long long __unset(long long b, long long i) { return b & (~(1UL << i)); }
long long __check(long long b, long long i) { return b & (1LL << i); }
long long mulmod(long long a, long long b, long long md) {
return (((a % md) * (b % md)) % md + md) % md;
}
long long addmod(long long a, long long b, long long md) {
return ((a % md + b % md) % md + md) % md;
}
long long submod(long long a, long long b, long long md) {
return (((a % md - b % md) % md) + md) % md;
}
long long divmod(long long a, long long b, long long md) {
return mulmod(a, powmod(b, md - 2, md), md);
}
const long long inf = 0xFFFFFFFFFFFFFFFL;
priority_queue<long long, vector<long long>, greater<long long> > pq;
long long __ceil(long long n, long long d) {
long long ans = n / d;
if (n % d != 0) ans++;
return ans;
}
signed main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long n;
cin >> n;
vector<long long> a(n);
for (long long i = 0; i < n; i++) cin >> a[i];
long long dpmn[n], dpmx[n];
dpmn[n - 2] = abs(a[n - 2] - a[n - 1]),
dpmx[n - 2] = abs(a[n - 2] - a[n - 1]);
for (long long i = n - 3; i >= 0; i--) {
dpmn[i] = min(abs(a[i] - a[i + 1]), abs(a[i] - a[i + 1]) - dpmx[i + 1]);
dpmx[i] = max(abs(a[i] - a[i + 1]), abs(a[i] - a[i + 1]) - dpmn[i + 1]);
}
cout << *max_element(dpmx, dpmx + n - 1) << "\n";
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(input())
a = list(map(int, input().split()))
def getAns(b):
res = 0
now = 0
for x in b:
if now > 0:
now += x
else:
now = x
res = max(res, now)
return res
b = [abs(a[i] - a[i + 1]) * (-1 if i & 1 else 1) for i in range(n - 1)]
res = getAns(b)
c = [b[i] * -1 for i in range(n - 1)]
res = max(res, getAns(c))
print(res)
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(raw_input())
arr=map(int,raw_input().split(" "))
arr1=[]
arr2=[]
mult=1
for i in range(len(arr)-1):
val = abs(arr[i]-arr[i+1])
arr1.append(mult*val)
arr2.append(-1*mult*val)
mult=mult*-1
max1=0
max2=0
curr=0
for val in arr1:
curr=curr+val
if curr>max1:
max1=curr
if curr<0:
curr=0
curr=0
for val in arr2:
curr=curr+val
if curr>max2:
max2=curr
if curr<0:
curr=0
if max1>max2:
print max1
else:
print max2 | PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Div2_407C {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int numI = Integer.parseInt(reader.readLine());
int[] items = new int[numI + 1];
StringTokenizer inputData = new StringTokenizer(reader.readLine());
for (int i = 1; i <= numI; i++) {
items[i] = Integer.parseInt(inputData.nextToken());
}
long[] pItems = new long[numI];
for (int i = 1; i < numI; i++) {
pItems[i] = ((i & 1) == 1 ? 1 : -1) * Math.abs(items[i] - items[i + 1]);
}
long ans = Long.MIN_VALUE;
long prev = 0;
for (int i = 1; i < numI; i++) {
prev = prev > 0 ? prev + pItems[i] : pItems[i];
if (prev > ans) {
ans = prev;
}
}
for (int i = 1; i < numI; i++) {
pItems[i] = -pItems[i];
}
prev = 0;
for (int i = 1; i < numI; i++) {
prev = prev > 0 ? prev + pItems[i] : pItems[i];
if (prev > ans) {
ans = prev;
}
}
System.out.println(ans);
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def ctd(chr): return ord(chr)-ord("a")
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
arr = RLL()
narr = []
for i in range(n-1):
narr.append(abs(arr[i+1]-arr[i]))
res = narr[0]
dp = [[0, 0] for _ in range(len(narr)+1)]
dp[1] = [narr[0], 0]
for i in range(2, len(narr)+1):
dp[i][0] = dp[i-1][1]+narr[i-1]
dp[i][1] = max(dp[i-1][0]-narr[i-1], 0)
res = max(res, max(dp[i]))
print(res)
if __name__ == "__main__":
main()
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.Point;
// SHIVAM GUPTA :
//NSIT
//decoder_1671
// STOP NOT TILL IT IS DONE OR U DIE .
// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................
// ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219
// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4
// FOR ANY ODD NO N : N,N-1,N-2
//ALL ARE PAIRWISE COPRIME
//THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS
// two consecutive odds are always coprime to each other
// two consecutive even have always gcd = 2 ;
public class Main
{
// static int[] arr = new int[100002] ; // static int[] dp = new int[100002] ;
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
String next(){
while(st==null || !st.hasMoreElements()){
try{
st= new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str=br.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
////////////////////////////////////////////////////////////////////////////////////
public static int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
/////////////////////////////////////////////////////////////////////////////////////////
public static int sumOfDigits(long n)
{
if( n< 0)return -1 ;
int sum = 0;
while( n > 0)
{
sum = sum + (int)( n %10) ;
n /= 10 ;
}
return sum ;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long arraySum(int[] arr , int start , int end)
{
long ans = 0 ;
for(int i = start ; i <= end ; i++)ans += arr[i] ;
return ans ;
}
/////////////////////////////////////////////////////////////////////////////////
public static int mod(int x)
{
if(x <0)return -1*x ;
else return x ;
}
public static long mod(long x)
{
if(x <0)return -1*x ;
else return x ;
}
////////////////////////////////////////////////////////////////////////////////
public static void swapArray(int[] arr , int start , int end)
{
while(start < end)
{
int temp = arr[start] ;
arr[start] = arr[end];
arr[end] = temp;
start++ ;end-- ;
}
}
//////////////////////////////////////////////////////////////////////////////////
public static int[][] rotate(int[][] input){
int n =input.length;
int m = input[0].length ;
int[][] output = new int [m][n];
for (int i=0; i<n; i++)
for (int j=0;j<m; j++)
output [j][n-1-i] = input[i][j];
return output;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
public static int countBits(long n)
{
int count = 0;
while (n != 0)
{
count++;
n = (n) >> (1L) ;
}
return count;
}
/////////////////////////////////////////// ////////////////////////////////////////////////
public static boolean isPowerOfTwo(long n)
{
if(n==0)
return false;
if(((n ) & (n-1)) == 0 ) return true ;
else return false ;
}
/////////////////////////////////////////////////////////////////////////////////////
public static int min(int a ,int b , int c, int d)
{
int[] arr = new int[4] ;
arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ;
return arr[0];
}
/////////////////////////////////////////////////////////////////////////////
public static int max(int a ,int b , int c, int d)
{
int[] arr = new int[4] ;
arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ;
return arr[3];
}
///////////////////////////////////////////////////////////////////////////////////
public static String reverse(String input)
{
StringBuilder str = new StringBuilder("") ;
for(int i =input.length()-1 ; i >= 0 ; i-- )
{
str.append(input.charAt(i));
}
return str.toString() ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static boolean sameParity(long a ,long b )
{
long x = a% 2L; long y = b%2L ;
if(x==y)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean isPossibleTriangle(int a ,int b , int c)
{
if( a + b > c && c+b > a && a +c > b)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////
static long xnor(long num1, long num2) {
if (num1 < num2) {
long temp = num1;
num1 = num2;
num2 = temp;
}
num1 = togglebit(num1);
return num1 ^ num2;
}
static long togglebit(long n) {
if (n == 0)
return 1;
long i = n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return i ^ n;
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static int xorOfFirstN(int n)
{
if( n % 4 ==0)return n ;
else if( n % 4 == 1)return 1 ;
else if( n % 4 == 2)return n+1 ;
else return 0 ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
public static int gcd(int a, int b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
public static long gcd(long a, long b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c , int d )
{
int temp = lcm(a,b , c) ;
int ans = lcm(temp ,d ) ;
return ans ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;
int ans = lcm(temp ,c) ;
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a , int b )
{
int gc = gcd(a,b);
return (a*b)/gc ;
}
public static long lcm(long a , long b )
{
long gc = gcd(a,b);
return (a*b)/gc ;
}
///////////////////////////////////////////////////////////////////////////////////////////
static boolean isPrime(long n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(long i = 2L; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
///////////////////////////////////////////////////////////////////////////
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime
// TRUE == COMPOSITE
// FALSE== 1
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ;
i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
///////////////////////////////////////////////////////////////////////////////////
public static void sortD(int[] arr , int s , int e)
{
sort(arr ,s , e) ;
int i =s ; int j = e ;
while( i < j)
{
int temp = arr[i] ;
arr[i] =arr[j] ;
arr[j] = temp ;
i++ ; j-- ;
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long countSubarraysSumToK(long[] arr ,long sum )
{
HashMap<Long,Long> map = new HashMap<>() ;
int n = arr.length ;
long prefixsum = 0 ;
long count = 0L ;
for(int i = 0; i < n ; i++)
{
prefixsum = prefixsum + arr[i] ;
if(sum == prefixsum)count = count+1 ;
if(map.containsKey(prefixsum -sum))
{
count = count + map.get(prefixsum -sum) ;
}
if(map.containsKey(prefixsum ))
{
map.put(prefixsum , map.get(prefixsum) +1 );
}
else{
map.put(prefixsum , 1L );
}
}
return count ;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// KMP ALGORITHM : TIME COMPL:O(N+M)
// FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING
//RETURN THE ARRAYLIST OF INDEXES
// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING
public static ArrayList<Integer> kmpAlgorithm(String str , String pat)
{
ArrayList<Integer> list =new ArrayList<>();
int n = str.length() ;
int m = pat.length() ;
String q = pat + "#" + str ;
int[] lps =new int[n+m+1] ;
longestPefixSuffix(lps, q,(n+m+1)) ;
for(int i =m+1 ; i < (n+m+1) ; i++ )
{
if(lps[i] == m)
{
list.add(i-2*m) ;
}
}
return list ;
}
public static void longestPefixSuffix(int[] lps ,String str , int n)
{
lps[0] = 0 ;
for(int i = 1 ; i<= n-1; i++)
{
int l = lps[i-1] ;
while( l > 0 && str.charAt(i) != str.charAt(l))
{
l = lps[l-1] ;
}
if(str.charAt(i) == str.charAt(l))
{
l++ ;
}
lps[i] = l ;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n
// TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1
// or n and the no will be coprime in nature
//time : O(n*(log(logn)))
public static void eulerTotientFunction(int[] arr ,int n )
{
for(int i = 1; i <= n ;i++)arr[i] =i ;
for(int i= 2 ; i<= n ;i++)
{
if(arr[i] == i)
{
arr[i] =i-1 ;
for(int j =2*i ; j<= n ; j+= i )
{
arr[j] = (arr[j]*(i-1))/i ;
}
}
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long nCr(int n,int k)
{
long ans=1L;
k=k>n-k?n-k:k;
int j=1;
for(;j<=k;j++,n--)
{
if(n%j==0)
{
ans*=n/j;
}else
if(ans%j==0)
{
ans=ans/j*n;
}else
{
ans=(ans*n)/j;
}
}
return ans;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static ArrayList<Integer> allFactors(int n)
{
ArrayList<Integer> list = new ArrayList<>() ;
for(int i = 1; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
public static ArrayList<Long> allFactors(long n)
{
ArrayList<Long> list = new ArrayList<>() ;
for(long i = 1L; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXN = 10000001;
static int spf[] = new int[MAXN];
static void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
// The above code works well for n upto the order of 10^7.
// Beyond this we will face memory issues.
// Time Complexity: The precomputation for smallest prime factor is done in O(n log log n)
// using sieve.
// Where as in the calculation step we are dividing the number every time by
// the smallest prime number till it becomes 1.
// So, letβs consider a worst case in which every time the SPF is 2 .
// Therefore will have log n division steps.
// Hence, We can say that our Time Complexity will be O(log n) in worst case.
static Vector<Integer> getFactorization(int x)
{
Vector<Integer> ret = new Vector<>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
public static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long knapsack(int[] weight,long value[],int maxWeight){
int n= value.length ;
//dp[i] stores the profit with KnapSack capacity "i"
long []dp = new long[maxWeight+1];
//initially profit with 0 to W KnapSack capacity is 0
Arrays.fill(dp, 0);
// iterate through all items
for(int i=0; i < n; i++)
//traverse dp array from right to left
for(int j = maxWeight; j >= weight[i]; j--)
dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);
/*above line finds out maximum of dp[j](excluding ith element value)
and val[i] + dp[j-wt[i]] (including ith element value and the
profit with "KnapSack capacity - ith element weight") */
return dp[maxWeight];
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// to return max sum of any subarray in given array
public static long kadanesAlgorithm(long[] arr)
{
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long kadanesAlgorithm(int[] arr)
{
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
///////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
public static long binarySerachGreater(int[] arr , int start , int end , int val)
{
// fing total no of elements strictly grater than val in sorted array arr
if(start > end)return 0 ; //Base case
int mid = (start + end)/2 ;
if(arr[mid] <=val)
{
return binarySerachGreater(arr,mid+1, end ,val) ;
}
else{
return binarySerachGreater(arr,start , mid -1,val) + end-mid+1 ;
}
}
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING
// JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive
//Function for swapping the characters at position I with character at position j
public static String swapString(String a, int i, int j) {
char[] b =a.toCharArray();
char ch;
ch = b[i];
b[i] = b[j];
b[j] = ch;
return String.valueOf(b);
}
//Function for generating different permutations of the string
public static void generatePermutation(String str, int start, int end)
{
//Prints the permutations
if (start == end-1)
System.out.println(str);
else
{
for (int i = start; i < end; i++)
{
//Swapping the string by fixing a character
str = swapString(str,start,i);
//Recursively calling function generatePermutation() for rest of the characters
generatePermutation(str,start+1,end);
//Backtracking and swapping the characters again.
str = swapString(str,start,i);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static long factMod(long n, long mod) {
if (n <= 1) return 1;
long ans = 1;
for (int i = 1; i <= n; i++) {
ans = (ans * i) % mod;
}
return ans;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long power(long x ,long n)
{
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n /= 2 ;
x = x*x ;
}
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static long powerMod(long x, long n, long mod) {
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans = 1;
while (n > 0) {
if (n % 2 == 1) ans = (ans * x) % mod;
x = (x * x) % mod;
n /= 2;
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/*
lowerBound - finds largest element equal or less than value paased
upperBound - finds smallest element equal or more than value passed
if not present return -1;
*/
public static long lowerBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static int lowerBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static long upperBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
public static int upperBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////////////
public static void printArray(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printArrayln(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printLArray(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printLArrayln(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printtwodArray(int[][] ans)
{
for(int i = 0; i< ans.length ; i++)
{
for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" ");
out.println() ;
}
out.println() ;
}
static long modPow(long a, long x, long p) {
//calculates a^x mod p in logarithmic time.
long res = 1;
while(x > 0) {
if( x % 2 != 0) {
res = (res * a) % p;
}
a = (a * a) % p;
x /= 2;
}
return res;
}
static long modInverse(long a, long p) {
//calculates the modular multiplicative of a mod m.
//(assuming p is prime).
return modPow(a, p-2, p);
}
static long modBinomial(long n, long k, long p) {
// calculates C(n,k) mod p (assuming p is prime).
long numerator = 1; // n * (n-1) * ... * (n-k+1)
for (int i=0; i<k; i++) {
numerator = (numerator * (n-i) ) % p;
}
long denominator = 1; // k!
for (int i=1; i<=k; i++) {
denominator = (denominator * i) % p;
}
// numerator / denominator mod p.
return ( numerator* modInverse(denominator,p) ) % p;
}
/////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
static ArrayList<Integer>[] tree ;
// static long[] child;
// static int mod= 1000000007 ;
// static int[][] pre = new int[3001][3001];
// static int[][] suf = new int[3001][3001] ;
//program to calculate noof nodes in subtree for every vertex including itself
public static void countNoOfNodesInsubtree(int child ,int par , int[] dp)
{
int count = 1 ;
for(int x : tree[child])
{
if(x== par)continue ;
countNoOfNodesInsubtree(x,child,dp) ;
count= count + dp[x] ;
}
dp[child] = count ;
}
public static void depth(int child ,int par , int[] dp , int d )
{
dp[child] =d ;
for(int x : tree[child])
{
if(x== par)continue ;
depth(x,child,dp,d+1) ;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
public static void solve()
{
FastReader scn = new FastReader() ;
//Scanner scn = new Scanner(System.in);
//int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;
// product of first 11 prime nos is greater than 10 ^ 12;
//ArrayList<Integer> arr[] = new ArrayList[n] ;
ArrayList<Integer> list = new ArrayList<>() ;
ArrayList<Long> listl = new ArrayList<>() ;
ArrayList<Integer> lista = new ArrayList<>() ;
ArrayList<Integer> listb = new ArrayList<>() ;
//ArrayList<String> lists = new ArrayList<>() ;
//HashMap<Integer,Integer> map = new HashMap<>() ;
HashMap<Long,Long> map = new HashMap<>() ;
HashMap<Integer,Integer> map1 = new HashMap<>() ;
HashMap<Integer,Integer> map2 = new HashMap<>() ;
//HashMap<String,Integer> maps = new HashMap<>() ;
//HashMap<Integer,Boolean> mapb = new HashMap<>() ;
//HashMap<Point,Integer> point = new HashMap<>() ;
Set<Integer> set = new HashSet<>() ;
Set<Integer> setx = new HashSet<>() ;
Set<Integer> sety = new HashSet<>() ;
StringBuilder sb =new StringBuilder("") ;
//Collections.sort(list);
//if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;
//else map.put(arr[i],1) ;
// if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;
// else map.put(temp,1) ;
//int bit =Integer.bitCount(n);
// gives total no of set bits in n;
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override
// public int compare(Pair a, Pair b) {
// if (a.first != b.first) {
// return a.first - b.first; // for increasing order of first
// }
// return a.second - b.second ; //if first is same then sort on second basis
// }
// });
int testcase = 1;
// testcase = scn.nextInt() ;
for(int testcases =1 ; testcases <= testcase ;testcases++)
{
//if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;
//if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;
// int n = scn.nextInt() ;
// tree = new ArrayList[n] ;
// for(int i = 0; i< n; i++)
// {
// tree[i] = new ArrayList<Integer>();
// }
// for(int i = 0 ; i <= n-2 ; i++)
// {
// int fv = scn.nextInt()-1 ; int sv = scn.nextInt()-1 ;
// tree[fv].add(sv) ;
// tree[sv].add(fv) ;
// }
int n = scn.nextInt() ;
long[] arr = new long[n] ;
for(int i = 0 ; i < n ; i++)arr[i] = scn.nextLong() ;
long[] b = new long[n] ;
long[] w = new long[n] ;
long temp = arr[n-2] - arr[n-1] ;
if(temp < 0)temp =-1*temp ;
b[n-2] =temp ;
w[n-2] = temp ;
long max = temp ;
for(int i = n-3 ; i >= 0 ; i--)
{
temp = arr[i] - arr[i+1] ;
b[i] = Math.max(Math.abs(temp) , Math.abs(temp) -w[i+1] ) ;
w[i] = Math.min(Math.abs(temp) , Math.abs(temp) -b[i+1] ) ;
if(b[i] > max)max = b[i] ;
}
//printLArrayln(b , 0 ,n-1) ;printLArrayln(w , 0 ,n-1) ;
out.println(max) ;
sb.delete(0 , sb.length()) ;
list.clear() ;listb.clear() ;
map.clear() ;
map1.clear() ;
map2.clear() ;
set.clear() ;sety.clear() ;
} // test case end loop
out.flush() ;
} // solve fn ends
public static void main (String[] args) throws java.lang.Exception
{
solve() ;
}
}
class Pair
{
int first ;
int second ;
@Override
public String toString() {
String ans = "" ;
ans += this.first ;
ans += " ";
ans += this.second ;
return ans ;
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
import java.io.*;
public class test{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++) a[i]=sc.nextInt();
boolean even=true;
int aa=0;
//even
long max=0;
long sum=0;
for(int i=0;i<n-1;i++){
if(even) aa=A(a,i);
else aa=-A(a,i);
even=!even;
if(aa>=0)sum+=aa;
else{
if(sum>max) max=sum;
sum+=aa;
if(sum<0)sum=0;
}
// System.out.println("1 "+sum);
if(sum>max) max=sum;
}
if(sum>max) max=sum;
//odd
sum=0;
even=true;
for(int i=1;i<n-1;i++){
if(even) aa=A(a,i);
else aa=-A(a,i);
even=!even;
if(aa>=0)sum+=aa;
else{
if(sum>max) max=sum;
sum+=aa;
if(sum<0)sum=0;
}
// System.out.println("2 "+sum);
if(sum>max) max=sum;
}
if(sum>max) max=sum;
System.out.println(max);
}
public static int A(int[] a,int i){
if(i>a.length-2) return 0;
return (int)Math.abs(a[i]-a[i+1]);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class recc788a {
static BufferedReader __in;
static PrintWriter __out;
static StringTokenizer input;
public static void main(String[] args) throws IOException {
__in = new BufferedReader(new InputStreamReader(System.in));
__out = new PrintWriter(new OutputStreamWriter(System.out));
int n = ri(), a[] = ria(n), mult = 1;
long d[] = new long[n];
for(int i = 0; i < n - 1; ++i) {
d[i + 1] = mult * abs(a[i + 1] - a[i]);
mult = -mult;
}
long msf = d[1], maxans = d[1], minsf = d[1], minans = d[1];
for(int i = 2; i < n; ++i) {
msf = max(msf + d[i], d[i]);
maxans = max(maxans, msf);
minsf = min(minsf + d[i], d[i]);
minans = min(minans, minsf);
}
prln(max(maxans, -minans));
close();
}
// references
// IBIG = 1e9 + 7
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int ni() {return Integer.parseInt(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | // package cp;
import java.io.*;
import java.util.*;
public class Cf_three {
static long max_sum(ArrayList<Long> arr) {
long cur_sum=0;long best_sum=0;
for (int i = 0; i < arr.size(); i++) {
cur_sum=Math.max(arr.get(i), cur_sum+arr.get(i));
best_sum=Math.max(best_sum, cur_sum);
}
return best_sum;
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
Readers.init(System.in);
int n=Readers.nextInt();
Cf_three obj=new Cf_three();
long[] a=new long[n];
for (int i = 0; i < a.length; i++) {
a[i]=Readers.nextLong();
}
ArrayList<Long> arr1=new ArrayList<>();
ArrayList<Long> arr2=new ArrayList<>();
arr1.add(Math.abs(a[1]-a[0]));
for (int i = 1; i < a.length-1; i++) {
if(i%2==1) {
arr2.add(Math.abs(a[i+1]-a[i]));
arr1.add(-Math.abs(a[i+1]-a[i]));
}
else {
arr1.add(Math.abs(a[i+1]-a[i]));
arr2.add(-Math.abs(a[i+1]-a[i]));
}
}
// System.out.println(arr1);
// System.out.println(arr2);
long ans1=obj.max_sum(arr1);
long ans2=obj.max_sum(arr2);
long ans=Math.max(ans1, ans2);
System.out.println(ans);
out.flush();
}
}
class Readers {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException{
return Long.parseLong(next());
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, k, i, sum1, sum2, dummy;
cin >> n;
vector<long long int> v, dp;
for (i = 0; i < n; i++) {
cin >> k;
v.push_back(k);
}
for (i = 0; i < n - 1; i++)
if (i % 2 == 0)
dp.push_back(fabs(v[i] - v[i + 1]));
else
dp.push_back(-fabs(v[i] - v[i + 1]));
v.clear();
sum1 = dp[0];
dummy = dp[0];
for (i = 1; i < n - 1; i++) {
dummy = fmax(dummy + dp[i], dp[i]);
sum1 = fmax(sum1, dummy);
}
for (i = 0; i < n - 1; i++) dp[i] = -dp[i];
sum2 = dp[0];
dummy = dp[0];
for (i = 1; i < n - 1; i++) {
dummy = fmax(dummy + dp[i], dp[i]);
sum2 = fmax(sum2, dummy);
}
cout << (long long int)fmax(sum1, sum2);
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Functions
{
static long DP[][];
static int arr[];
static int n;
public static long solve(int f,int idx)
{
if(idx == n - 1)
return 0;
if(DP[f][idx] != -1)
return DP[f][idx];
long curr = Math.abs(arr[idx] - arr[idx + 1]);
if(f == 1)
curr *= -1;
return DP[f][idx] = Math.max(curr, curr + solve(f ^ 1,idx + 1));
}
public static void main(String[]args)throws Throwable
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
DP = new long[2][n + 1];
Arrays.fill(DP[0], -1); Arrays.fill(DP[1], -1);
arr = new int[n];
for(int i = 0 ; i < n ; ++i)
{
arr[i] = sc.nextInt();
}
long max = -(1L << 55);
for(int i = 0 ; i < n ; ++i)
max = Math.max(max, solve(0,i));
System.out.println(max);
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); }
String next() throws IOException
{
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Template implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
class GraphBuilder {
int n, m;
int[] x, y;
int index;
int[] size;
GraphBuilder(int n, int m) {
this.n = n;
this.m = m;
x = new int[m];
y = new int[m];
size = new int[n];
}
void add(int u, int v) {
x[index] = u;
y[index] = v;
size[u]++;
size[v]++;
index++;
}
int[][] build() {
int[][] graph = new int[n][];
for (int i = 0; i < n; i++) {
graph[i] = new int[size[i]];
}
for (int i = m - 1; i >= 0; i--) {
graph[x[i]][--size[x[i]]] = y[i];
graph[y[i]][--size[y[i]]] = x[i];
}
return graph;
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = readInt();
}
return res;
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
<T> List<T>[] createGraphList(int size) {
List<T>[] list = new List[size];
for (int i = 0; i < size; i++) {
list[i] = new ArrayList<>();
}
return list;
}
public static void main(String[] args) {
new Template().run();
// new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB");
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
if (System.getProperty("ONLINE_JUDGE") == null) {
time();
memory();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
void solve() throws IOException {
int n = readInt();
int[] a = readIntArray(n);
int[] d = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
d[i] = Math.abs(a[i] - a[i + 1]);
}
long best = Long.MIN_VALUE;
long[] answer = new long[d.length];
for (int i=d.length-1;i>=0;i--) {
if (i - 1 >= 0) {
answer[i] = d[i] - d[i - 1];
if (i + 2 < d.length) {
answer[i] += answer[i + 2];
}
answer[i] = Math.max(answer[i], 0);
}
long curAns = d[i];
if (i + 2 < d.length) {
curAns += answer[i + 2];
}
best = Math.max(best, curAns);
}
out.println(best);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author root
*/
public class C {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int a[] = new int[n];
String tokens[] = br.readLine().split(" ");
for(int i = 0;i<n;i++) a[i] = Integer.parseInt(tokens[i]);
long res = getMaxOfFunction(a);
System.out.println(res);
}
private static long getMaxOfFunction(int a[]){
long b[] = new long[a.length];
long c[] = new long[a.length];
int one = 1;
for(int i = 0;i<a.length-1;i++){
b[i] = Math.abs((long)(a[i+1]-a[i]))*one;
c[i] = -b[i];
one*=-1;
}
return Math.max(getMaxSegmentSum(b), getMaxSegmentSum(c));
}
private static long getMaxSegmentSum(long b[]){
long prefMin = 0, prefMax = 0, prefSum = 0;
for(int i = 0;i<b.length;i++){
prefSum+=b[i];
prefMin= Math.min(prefSum, prefMin);
prefMax = Math.max(prefSum, prefMax);
}
return prefMax-prefMin;
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | ### @author egaeus
### @mail [email protected]
### @veredict
### @url https://codeforces.com/problemset/problem/788/A
### @category
### @date 13/11/2019
def f(list):
listA = []
listB = [0]
res = 0
for i in range(len(list)):
res = max(res, list[i])
if i%2==0:
if len(listA) > 0:
listA.append(list[i]+listA[len(listA)-1])
else:
listA.append(list[i])
else:
if len(listB) > 0:
listB.append(list[i]+listB[len(listB)-1])
else:
listB.append(list[i])
s = 0
for i in range(len(listA)):
if i > 0:
s = max(s, listB[i]-listA[i-1])
res = max(res, listA[i] - listB[i] + s)
return res
N = int(input())
list = []
line = input().split()
last = int(line[0])
for i in range(1,N):
n = int(line[i])
list.append(abs(last - n))
last = n
v = f(list)
del list[0]
print(max(v,f(list))) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n=int(input())
b=list(map(int,input().split()))
s1=0
s2=0
j=0
c=[]
while(j<n-1):
c.append(abs(b[j+1]-b[j]))
j+=1
j=0
p=0
r=0
while(j<(n-1)):
if (j+1)<(n-1):
r=max(c[j]-c[j+1],r+c[j]-c[j+1])
p = max(p, r +c[j + 1])
else:
r=max(c[j],r+c[j])
p=max(p,r)
j+=2
j=1
r=0
while(j<(n-1)):
if (j+1)<(n-1):
r=max(c[j]-c[j+1],r+c[j]-c[j+1])
p = max(p, r+c[j+1])
else:
r=max(c[j],r+c[j])
p=max(p,r)
j+=2
print(p)
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn Agrawal coderbond007
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public static FastReader check;
public void solve(int testNumber, FastReader in, PrintWriter out) {
check = in;
int n = ni();
long[] a = nal(n);
long[] sum = new long[n];
for (int i = 1; i < n; i++) {
sum[i - 1] = Math.abs(a[i] - a[i - 1]);
}
long ans = 0;
long max = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
ans += sum[i];
} else {
ans -= sum[i];
}
max = Math.max(max, ans);
if (ans < 0) {
ans = 0;
}
}
ans = 0;
for (int i = 1; i < n; i++) {
if (i % 2 == 1) {
ans += sum[i];
} else {
ans -= sum[i];
}
max = Math.max(max, ans);
if (ans < 0) {
ans = 0;
}
}
out.println(max);
}
private static int ni() {
return check.nextInt();
}
private static long nl() {
return check.nextLong();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nl();
return a;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c == ',') {
c = read();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| JAVA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.