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
//package round407; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); long[] b = new long[n-1]; for(int i = 0;i < n-1;i++){ b[i] = Math.abs(a[i] - a[i+1]); if(i % 2 == 1)b[i] = -b[i]; } // -3 2 -1 2 long[] bcum = new long[n]; for(int i = 0;i < n-1;i++){ bcum[i+1] = bcum[i] + b[i]; } long ret = Long.MIN_VALUE; { long min = Long.MAX_VALUE / 2; for(int i = 0;i < n;i++){ ret = Math.max(ret, bcum[i] - min); if(i % 2 == 0){ min = Math.min(min, bcum[i]); } } } { long min = Long.MAX_VALUE / 2; for(int i = 0;i < n;i++){ ret = Math.max(ret, -bcum[i] - min); if(i % 2 == 1){ min = Math.min(min, -bcum[i]); } } } out.println(ret); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
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()) arr=list(map(int,input().split())) new=[] c=1 for i in range(n-1): new.append(abs(arr[i]-arr[i+1])*c) c*=-1 s=0 s1=0 m=0 for i in range(n-1): s+=new[i] if s<0: s=0 if i>0: s1+=-new[i] if s1<0: s1=0 m=max(m,s1) m=max(m,s) print(m)
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 mod = 1000000007; long long INF = 1e9; const long long LINF = (long long)1e16 + 5; int main() { int n; cin >> n; long long int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } long long int sub[n - 1]; for (int i = 0; i < n - 1; i++) { if (i % 2 == 0) sub[i] = abs(a[i + 1] - a[i]); else sub[i] = -1 * abs(a[i] - a[i + 1]); } long long int sum[n - 1]; memset(sum, 0, sizeof(sum)); sum[0] = sub[0]; for (int i = 1; i < n - 1; i++) { sum[i] = sum[i - 1] + sub[i]; } long long int mx[n - 1], mn[n - 1]; for (int i = 0; i < n - 1; i++) { mx[i] = -1000000000; mn[i] = 10000000000; } mx[n - 2] = sum[n - 2]; mn[n - 2] = sum[n - 2]; for (int i = n - 3; i >= 0; i--) { mx[i] = max(mx[i + 1], sum[i]); mn[i] = min(mn[i + 1], sum[i]); } long long int ans = -1000000000; for (int i = 0; i < n - 2; i++) { if (i % 2 == 0) { ans = max(ans, sub[i]); if (i == 0) ans = max(ans, mx[i + 1]); else ans = max(ans, mx[i + 1] - sum[i - 1]); } else { ans = max(ans, -1 * sub[i]); ans = max(ans, -1 * (mn[i + 1] - sum[i - 1])); } } if ((n - 2) % 2 == 0) ans = max(sub[n - 2], ans); else ans = max(-1 * sub[n - 2], ans); 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
from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd from collections import deque from bisect import bisect_left,bisect_right n=int(input()) l=list(map(int,input().split())) z=[] for i in range(n-1): z.append(abs(l[i]-l[i+1])) ans=0 a,b=0,0 for i in z: a,b=max(b+i,0),max(a-i,0) ans=max(ans,a+b) 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
n = map(int, raw_input().split()) tab = map(int, raw_input().split()) acc = 0 mx = 0 mn = 0 k = 1 for i in range(len(tab)-1): acc += abs(tab[i] - tab[i + 1]) * k k *= (-1) mx = max(mx, acc) mn = min(mn, acc) print abs(mx-mn)
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> const int N = 100010; int a[N], _abs[N], n; std::multiset<long long> set = {0}; long long pre[N]; int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); _abs[i] = std::abs(a[i - 1] - a[i]); } for (int i = 1; i < n; ++i) { pre[i] = pre[i - 1] + (i & 1 ? _abs[i] : -_abs[i]); set.insert(pre[i]); } long long ans = -LLONG_MAX; for (int i = 0; i < n - 1; ++i) { auto u = set.find(pre[i]); set.erase(u); if (i & 1) { auto u = set.begin(); ans = std::max(pre[i] - *u, ans); } else { auto u = set.end(); --u; ans = std::max(*u - pre[i], ans); } } return printf("%I64d\n", ans), 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=input() a=map(int,raw_input().split()) b=[abs(a[i]-a[i-1]) for i in range(1,n)] a=b[0] s=t=0 for i in range(n-1): d=(b[i],-b[i])[i%2] s+=d t-=d a=max(a,s,t) s=max(s,0) t=max(t,0) print a
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.*; 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
def solve(): n = int(input()) a = tuple(map(int, input().split())) d = [] for i in range(0, n - 1): d.append(abs(a[i] - a[i + 1])) subtracted = [0 for i in range(n - 1)] added = [0 for i in range(n - 1)] if n == 2: print(d[0]) else: added[0] = d[0] added[1] = d[1] subtracted[1] = added[0] - d[1] for i in range(2, n - 1): added[i] = max(d[i], subtracted[i - 1] + d[i]) subtracted[i] = added[i - 1] - d[i] res = 0 for i in range(n - 1): res = max(res, max(added[i], subtracted[i])) print(res) solve()
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()) l=list(map(int,input().split())) a=[0]*(n-1) for i in range(n-1): a[i]=abs(l[i]-l[i+1])*(-1)**(i) if n==2: print(a[0]) sys.exit() a1=[0]*(n-2) for i in range(1,n-1): a1[i-1]=abs(l[i]-l[i+1])*(-1)**(i-1) ans=a[0] cur=a[0] for i in range(1,n-1): cur=max(cur+a[i],a[i]) ans=max(ans,cur) ans1=a1[0] cur1=a1[0] for i in range(1,n-2): cur1=max(cur1+a1[i],a1[i]) ans1=max(ans1,cur1) print(max(ans,ans1))
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 = [] for i in range(n - 1): B.append(abs(A[i] - A[i + 1])) dpmin = [0] * n dpmax = [0] * n for i in range(n - 2, -1, -1): dpmax[i] = B[i] dpmin[i] = B[i] dpmin[i] = min(dpmin[i], B[i] - dpmax[i + 1]) dpmax[i] = max(dpmax[i], B[i] - dpmin[i + 1]) print(max(dpmax))
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.*; public class Functions_again { public static void main(String args[]) throws Exception { BufferedReader f=new BufferedReader(new InputStreamReader(System.in)); int size=Integer.parseInt(f.readLine()); long[][] dp=new long[size][2]; int[] arr=new int[size]; StringTokenizer st=new StringTokenizer(f.readLine()); for(int x=0;x<size;x++) arr[x]=Integer.parseInt(st.nextToken()); for(int x=1;x<size;x++) { dp[x][0]=Math.max(dp[x-1][1]+Math.abs(arr[x]-arr[x-1]),Math.abs(arr[x]-arr[x-1])); dp[x][1]=Math.max(0,dp[x-1][0]-Math.abs(arr[x]-arr[x-1])); } long max=0; for(int x=0;x<size;x++) for(int y=0;y<2;y++) max=Math.max(max,dp[x][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.*; public class C { public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int [] a=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); long [] b=new long [n-1]; int p=1; for(int i=0;i<n-1;i++){ b[i]=p*Math.abs(a[i]-a[i+1]); p*=(-1); } long max=Long.MIN_VALUE; long sum=0; for(int i=0;i<n-1;i++){ sum+=b[i]; sum=Math.max(sum, 0); max=Math.max(max, sum); if(sum==0 && i%2==0) i++; } p=-1; for(int i=0;i<n-1;i++){ b[i]=p*Math.abs(a[i]-a[i+1]); p*=(-1); } sum=0; for(int i=1;i<n-1;i++){ sum+=b[i]; sum=Math.max(sum, 0); max=Math.max(max, sum); if(sum==0 && i%2==1) i++; } // System.out.println(Arrays.toString(b)); pw.println(max); pw.flush(); pw.close(); } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() {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
n=int(input()) a=list(map(int, input().split(" "))) d=[] for k in range(n-1): d.append(abs(a[k]-a[k+1])) for k in range(n-1): if(k%2): d[k]*=-1 maxsum=0 minsum=0 curmax=0 curmin=0 for k in range(n-1): if(d[k]>0): minsum=min(curmin, minsum) curmax+=d[k] curmin+=d[k] if(curmin>0): curmin=0 else: maxsum=max(maxsum, curmax) curmin+=d[k] curmax+=d[k] if(curmax<0): curmax=0 maxsum=max(maxsum, curmax) minsum=min(minsum, curmin) print(max(abs(maxsum), abs(minsum)))
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 FunctionsAgain_CF788A { 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 num [] = new int [n]; for(int i = 0; i < n; i++) num [i] = sc.nextInt(); int diff [] = new int [n-1]; for(int i = 1; i < n; i++) diff[i - 1] = Math.abs(num[i] - num[i - 1]); long max = 0; long sum = 0; boolean add = true; for(int i = 0; i < n - 1 ; i++){ if(add) sum += diff[i]; else sum -= diff[i]; add = !add; max = Math.max(sum, max); if(sum < 0) sum = 0; } sum = 0; add = false; for(int i = 0; i < n - 1 ; i++){ if(add) sum+= diff[i]; else sum -= diff[i]; add = !add; max = Math.max(sum, max); if(sum < 0) sum = 0; } out.println(max); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } 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 { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } 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.InputStream; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.math.BigDecimal; import java.util.*; import java.util.stream.Stream; /** * * @author Pradyumn Agrawal coderbond007 */ public class C{ public static InputStream inputStream = System.in; public static StringTokenizer tok = null; public static BufferedReader br = new BufferedReader(new InputStreamReader(inputStream), 32768); public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static void main(String[] args) throws java.lang.Exception{ new Thread(null, new Runnable() { public void run() { try { new C().run(); out.close(); } catch(IOException e){ } } }, "1", 1 << 26).start(); } public void run() throws IOException { 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 void debug(Object... objects){ if(objects.length > 0){ out.println(Arrays.deepToString(objects)); } } public static int ni() throws IOException { return Integer.parseInt(ns()); } public static long nl() throws IOException { return Long.parseLong(ns()); } public static double nd() throws IOException { return Double.parseDouble(ns()); } public static char nc() throws IOException { return ns().charAt(0); } public static BigInteger nextBigInteger() throws IOException { return new BigInteger(ns()); } public static String ns() throws IOException { while(tok == null || !tok.hasMoreTokens()){ try { tok = new StringTokenizer(br.readLine()); } catch (IOException e){ throw new RuntimeException(e); } } return tok.nextToken(); } public static int[] na(int n) throws IOException { int[] a = new int[n]; for(int i = 0;i < n; i++){ a[i] = ni(); } return a; } public static long[] nal(int n) throws IOException { long[] a = new long[n]; for(int i = 0;i < n; i++){ a[i] = nl(); } return a; } public static char[] ns(int n) throws IOException { return ns().substring(0,n).toCharArray(); } public static char[][] nm(int n, int m) throws IOException{ char[][] map = new char[n][]; for(int i = 0;i < n; i++){ map[i] = ns(m); } return map; } public static String readLine() { try { return br.readLine(); } catch(IOException e){ throw new RuntimeException(e); } } }
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()) a = list(map(int, input().split())) d = [[] for i in range(2)] pre = a[0] mi = 1 for i in range(1, n): d[0].append(mi * abs(pre - a[i])) d[1].append(-mi * abs(pre - a[i])) pre = a[i] mi *= -1 m = len(d[0]) L = [[0] * m for i in range(2)] R = [[0] * m for i in range(2)] L[0][0] = d[0][0] L[1][0] = d[1][0] R[0][0] = d[0][0] R[1][0] = d[1][0] for k in range(2): for i in range(1, m): if L[k][i - 1] >= R[k][i - 1]: L[k][i] = L[k][i - 1] else: L[k][i] = R[k][i - 1] if R[k][i - 1] + d[k][i] < d[k][i]: R[k][i] = d[k][i] else: R[k][i] = R[k][i - 1] + d[k][i] if L[0][-1] > R[0][-1]: num1 = L[0][-1] else: num1 = R[0][-1] if L[1][-1] > R[1][-1]: num2 = L[1][-1] else: num2 = R[1][-1] print(max(num1, num2))
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; struct DP_NODE { long long int maxval, minval; }; DP_NODE dp[200005]; long long int a[200005]; int n; int main(int argc, char* argv[]) { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%I64d", &a[i]); dp[n - 2].maxval = abs(a[n - 2] - a[n - 1]); dp[n - 2].minval = 0; long long int ans = dp[n - 2].maxval; for (int i = n - 3; i >= 0; --i) { long long int tmp = abs(a[i] - a[i + 1]); dp[i].maxval = max(tmp, -dp[i + 1].minval + tmp); dp[i].minval = min(tmp, -dp[i + 1].maxval + tmp); ans = max(ans, dp[i].maxval); } printf("%I64d\n", 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; const int N = 100005; const int INF = 0x3f3f3f3f; inline long long lllabs(long long x) { return x < 0 ? -x : x; } long long a[N]; int main() { int n; while (~scanf("%d", &n)) { a[0] = 0; for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); for (int i = 2; i <= n; i++) a[i - 1] = lllabs(a[i] - a[i - 1]); long long ans = 0, sum = 0, k = 1; for (int i = 1; i < n; i++) { sum += k * a[i]; k = -k; ans = max(ans, sum); if (sum < 0) { sum = 0; k = 1; } } sum = 0; k = 1; for (int i = 2; i < n; i++) { sum += k * a[i]; k = -k; ans = max(ans, sum); if (sum < 0) { sum = 0; k = 1; } } printf("%lld\n", 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 arr[100005], dif[100005]; int main() { long long n, i; cin >> n; for (i = 0; i < n; i++) cin >> arr[i]; for (i = 0; i < n - 1; i++) { dif[i] = abs(arr[i] - arr[i + 1]); } for (i = 0; i < n - 1; i++) { if (i & 1) dif[i] = -dif[i]; } long long mxm = dif[0], cur = dif[0]; for (i = 1; i < n - 1; i++) { cur = max(dif[i], dif[i] + cur); mxm = max(mxm, cur); } for (i = 0; i < n - 1; i++) { dif[i] = -dif[i]; } long long a = dif[0], b = dif[0]; for (i = 1; i < n - 1; i++) { a = max(dif[i], dif[i] + a); b = max(b, a); } cout << max(mxm, b) << 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.*; import java.util.*; /** * @author Aydar Gizatullin a.k.a. lightning95, [email protected] * Created on 17.02.17. */ public class Main { class Pair { int a, b; Pair(int x, int y) { a = x; b = y; } } private void solve() { int n = rw.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = rw.nextInt(); } int[] b = new int[n - 1]; for (int i = 0; i < n - 1; ++i) { b[i] = Math.abs(a[i] - a[i + 1]) * (i % 2 != 0 ? -1 : 1); } int[] c = new int[n - 1]; for (int i = 1; i < n - 1; ++i) { c[i] = Math.abs(a[i] - a[i + 1]) * (i % 2 == 0 ? -1 : 1); } long[] sum1 = new long[n]; long min_sum = 0; long sum = 0; long ans = 0; for (int i = 0; i < n - 1; ++i) { sum += b[i]; ans = Math.max(ans, sum - min_sum); min_sum = Math.min(min_sum, sum); } min_sum = 0; sum = 0; for (int i = 1; i < n - 1; ++i){ sum += c[i]; ans = Math.max(ans, sum - min_sum); min_sum = Math.min(min_sum, sum); } rw.println(ans); } private RW rw; private String FILE_NAME = "file"; public static void main(String[] args) { new Main().run(); } private void run() { rw = new RW(FILE_NAME + ".in", FILE_NAME + ".out"); solve(); rw.close(); } private class RW { private StringTokenizer st; private PrintWriter out; private BufferedReader br; private boolean eof; RW(String inputFile, String outputFile) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); File f = new File(inputFile); if (f.exists() && f.canRead()) { try { br = new BufferedReader(new FileReader(inputFile)); out = new PrintWriter(new FileWriter(outputFile)); } catch (IOException e) { e.printStackTrace(); } } } private String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { eof = true; return "-1"; } } return st.nextToken(); } private long nextLong() { return Long.parseLong(next()); } private int nextInt() { return Integer.parseInt(next()); } private void println() { out.println(); } private void println(Object o) { out.println(o); } private void print(Object o) { out.print(o); } private void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } 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
#include <bits/stdc++.h> using namespace std; const int MAX = 1e5 + 9; int main() { long long int a[MAX], dif[MAX], n, i; cin >> n; for (i = 1; i <= n; i++) { cin >> a[i]; } for (i = 1; i < n; i++) { if (i % 2) dif[i] = dif[i - 1] + abs(a[i] - a[i + 1]); else dif[i] = dif[i - 1] - abs(a[i] - a[i + 1]); } sort(dif, dif + n); cout << dif[n - 1] - dif[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; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n; cin >> n; vector<long long> vec(n + 1); for (long long i = 1; i <= n; i++) cin >> vec[i]; vec[0] = vec[1]; long long dp[2][n], x; memset(dp, 0, sizeof(dp)); long long ans = 0; for (long long i = 1; i < n; i++) { dp[0][i] = max( dp[0][i - 1] + abs(vec[i] - vec[i + 1]) * (x = i % 2 ? 1 : -1), 0LL); dp[1][i] = max( dp[1][i - 1] + abs(vec[i] - vec[i + 1]) * (x = i % 2 ? -1 : 1), 0LL); ans = max(ans, max(dp[0][i], dp[1][i])); } cout << ans << '\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
def maxSubArraySum(a,size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_ending_here < 0: max_ending_here = 0 # Do not compare for all elements. Compare only # when max_ending_here > 0 elif (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far n = int(input()) a = list(map(int,input().split())) c = [] for i in range(len(a)-1): c.append(abs(a[i]-a[i+1])) p = [] q = [] for i in range(len(c)): p.append(c[i]*pow(-1,i)) for i in range(len(c)): q.append(c[i]*pow(-1,i+1)) print(max(maxSubArraySum(p,len(p)),maxSubArraySum(q,len(q))))
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.*; public class Solution{ static 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; } } static long ninf = Long.MIN_VALUE; public static void main(String[] args){ FastReader sc = new FastReader(); int n = sc.nextInt(); long[] arr = new long[n]; for(int i=0;i<n;i++) arr[i] = sc.nextLong(); for(int i=0;i<n-1;i++){ arr[i] = Math.abs(arr[i]-arr[i+1]); arr[i] *= ((i%2==0)?1:-1); } arr[n-1]=0; long max_ans=ninf, cur=0; for(int i=0;i<n;i++){ cur+=arr[i]; if(cur<0) cur=0; max_ans = Math.max(max_ans, cur); } cur=0; for(int i=0;i<n;i++){ arr[i] *= (-1); } for(int i=0;i<n;i++){ cur+=arr[i]; if(cur<0) cur=0; max_ans = Math.max(max_ans, cur); } System.out.println(max_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; const int N = 100010; int n; long long int a[N], b[N], s1[N], s2[N], mns, ans; long long maxSubArraySum(long long x[], int siz) { long long max_so_far = x[1]; long long curr_max = x[1]; for (int i = 2; i < siz; i++) { curr_max = max(x[i], curr_max + x[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far; } 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 = 1; i < n; i++) if (i & 1) s1[i] = b[i], s2[i] = -b[i]; else s1[i] = -b[i], s2[i] = b[i]; long long int res1, res2; res1 = maxSubArraySum(s1, n); res2 = maxSubArraySum(s2, n); ans = max(res1, res2); printf("%lld\n", 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
#include <bits/stdc++.h> using namespace std; inline char tc(void) { static char fl[10000], *A = fl, *B = fl; return A == B && (B = (A = fl) + fread(fl, 1, 10000, stdin), A == B) ? EOF : *A++; } inline int read(void) { int a = 0, f = 1; char c; while ((c = tc()) < '0' || c > '9') c == '-' ? f = -1 : 0; while (c >= '0' && c <= '9') a = a * 10 + c - '0', c = tc(); return a * f; } int n, a[200005]; long long mix[2], now[2], ans; int main(void) { register int i; n = read(); for (i = 1; i <= n; ++i) a[i] = read(); mix[0] = mix[1] = 0; for (i = 1; i < n; ++i) { now[0] += (i & 1 ? -1 : 1) * abs(a[i] - a[i + 1]), now[1] += (i & 1 ? 1 : -1) * abs(a[i] - a[i + 1]); mix[0] = min(mix[0], now[0]), mix[1] = min(mix[1], now[1]); ans = max(ans, max(now[1] - mix[1], now[0] - mix[0])); } printf("%lld\n", 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; int a[100005], p[100005]; long long z = 1, f[100005][2], ans; int main() { int i, j, n, m; memset(f, 0xc0, sizeof(f)); scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%d", &a[i]); for (i = 1; i <= n; i++) p[i] = abs(a[i + 1] - a[i]); f[1][1] = p[1]; ans = p[1]; for (i = 2; i <= n - 1; i++) { f[i][1] = p[i]; f[i][1] = max(f[i][1], f[i - 1][0] + p[i]); f[i][0] = f[i - 1][1] - p[i]; ans = max(ans, max(f[i][0], f[i][1])); } printf("%lld", 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
import java.util.*; import java.io.*; public class C789 { public static void main(String[] args) { InputReader s = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); /*My code starts here.*/ int n = s.nextInt(); long arr[] = new long[n-1]; long prev = s.nextInt(); long max = -1; for(int i=1;i<n;i++){ int tmp = s.nextInt(); arr[i-1] = Math.abs(tmp - prev); prev = tmp; if(max<arr[i-1]) max = arr[i-1]; } max = function(arr,max); out.println(max); /*My code ends here.*/ out.close(); } static long function(long[] arr,long max) { long sum = 0,k; int i=0; while(i<arr.length){ k = arr[i]; if((i&1)==1) k = -arr[i]; sum += k; if(sum<0){ sum = 0; } else{ if(sum>max) max = sum; } i++; } sum = 0; i = 0; while(i<arr.length){ k = arr[i]; if((i&1)==0) k = -arr[i]; sum += k; if(sum<0){ sum = 0; } else{ if(sum>max) max = sum; } i++; } return max; } static long PowerMod(long a, long b, long m) { long tempo; if (b == 0) tempo = 1; else if (b == 1) tempo = a; else { long temp = PowerMod(a, b / 2, m); if (b % 2 == 0) tempo = (temp * temp) % m; else tempo = ((temp * temp) % m) * a % m; } return tempo; } static class Node implements Comparable<Node> { int num, freq, idx; public Node(int u, int v, int idx) { this.num = u; this.freq = v; this.idx = idx; } public int compareTo(Node n) { if (this.freq == n.freq) return Integer.compare(this.num, n.num); return Integer.compare(-this.freq, -n.freq); } } static class InputReader { private InputStream stream; private 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 int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = 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 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
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); long long n; cin >> n; long long a[n]; for (long long i = 0; i < n; i++) cin >> a[i]; long long f[n - 1]; long long s[n - 1]; for (long long i = 0; i < n - 1; i++) { f[i] = abs((a[i] - a[i + 1])) * pow(-1, i); s[i] = abs((a[i] - a[i + 1])) * (pow(-1, i + 1)); } long long curr = f[0]; long long max_sofar = f[0]; for (long long i = 1; i <= n - 2; i++) { curr = max(f[i], curr + f[i]); max_sofar = max(max_sofar, curr); } if (n > 2) curr = s[1]; max_sofar = max(max_sofar, curr); for (long long i = 2; i <= n - 2; i++) { curr = max(s[i], curr + s[i]); max_sofar = max(max_sofar, curr); } cout << max_sofar; 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
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase def solve(d): ma, mas = 0, 0 for i in d: mas += i mas = max(mas, 0) ma = max(mas, ma) return ma def main(): n=int(input()) a=list(map(int,input().split())) d,c=[],[] for i in range(n-1): d.append(abs(a[i]-a[i+1])*(-1 if i&1 else 1)) c.append(abs(a[i]-a[i+1])*(1 if i&1 else -1)) print(max(solve(d),solve(c))) # 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") 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
#include <bits/stdc++.h> using namespace std; long long v[200050], sp1[200050], sp2[200050]; int main() { int n, i, k, first, iteratii = 0; long long minsp1 = 0, minsp2 = 0, ans = -0x3f3f3f3fLL; cin >> n; for (i = 1; i <= n; ++i) cin >> v[i]; for (i = 1; i < n; ++i) { sp1[i] = sp1[i - 1] + abs(v[i] - v[i + 1]) * ((i % 2 == 0) ? -1 : 1); sp2[i] = sp2[i - 1] + abs(v[i] - v[i + 1]) * ((i % 2 == 0) ? 1 : -1); ans = max(ans, sp1[i] - minsp1); ans = max(ans, sp2[i] - minsp2); minsp1 = min(minsp1, sp1[i]); minsp2 = min(minsp2, sp2[i]); } 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
import java.util.Scanner; public class Frodo { static long max(int[] a) { long maxsofar = 0, maxhere = 0; for (int i = 0; i < a.length; i++) { maxhere = Math.max(maxhere + a[i], 0); maxsofar = Math.max(maxsofar, maxhere); } return maxsofar; } static int[] arr, a1, a2; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } a1 = new int[n]; a2 = new int[n]; for (int i = 0; i < n - 1; i++) { a1[i] = Math.abs(arr[i] - arr[i + 1]) * ((i % 2) == 0 ? -1 : 1); a2[i] = Math.abs(arr[i] - arr[i + 1]) * ((i % 2) == 1 ? -1 : 1); } System.out.println(Math.max(max(a1), max(a2))); } }
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.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); long[] a = new long[n]; long best = Long.MIN_VALUE; for (int i = 0; i < n; i++) { a[i] = in.nextLong(); if (i > 0) { best = Math.max(best, Math.abs(a[i] - a[i - 1])); } } long s1 = 0; long s2 = 0; for (int i = 1; i < n; i++) { if (i % 2 != 0) { s1 += Math.abs(a[i] - a[i - 1]); s2 -= Math.abs(a[i] - a[i - 1]); } else { s1 -= Math.abs(a[i] - a[i - 1]); s2 += Math.abs(a[i] - a[i - 1]); } s1 = Math.max(s1, 0); s2 = Math.max(s2, 0); best = Math.max(best, s1); best = Math.max(best, s2); } out.println(best); } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(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 sys import math n = int(sys.stdin.readline().strip()) a=map(int,sys.stdin.readline().split()) v=[] for i in range(n-1): v.append(abs(a[i]-a[i+1])) sm=0 mx=0 for i in range(n-1): if i%2==0: sm+=v[i] else: sm-=v[i] if sm>mx:mx=sm if sm<0:sm=0 sm=0 for i in range(n-1): if i%2==1: sm+=v[i] else: sm-=v[i] if sm>mx:mx=sm if sm<0:sm=0 print mx
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> using namespace std; int n; vector<long long int> v; long long int im[2][100002]; long long int mx[2][100002]; int main() { cin >> n; for (int i = 0; i < n; i++) { int a; scanf("%d", &a); v.push_back(a); } for (int i = 0; i + 1 < v.size(); i++) { for (int j = 0; j < 2; j++) { if ((i % 2) == j) { im[j][i] = abs(v[i + 1] - v[i]); } else { im[j][i] = -abs(v[i + 1] - v[i]); } if (i) { im[j][i] += im[j][i - 1]; } } } for (int i = v.size() - 1; i >= 0; i--) { for (int j = 0; j < 2; j++) { mx[j][i] = im[j][i]; if (i + 1 < n - 1) mx[j][i] = max(mx[j][i], mx[j][i + 1]); } } long long int ans = LLONG_MIN; for (int i = 0; i + 1 < n; i++) { int j = (i % 2); long long int lef = 0; if (i) { lef -= im[j][i - 1]; } lef += mx[j][i]; ans = max(ans, lef); } printf("%lld\n", 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
n = int(input()) l = list(map(int, input().split(" "))) d = [] for i in range(n-1): a = 1 if i%2: a = -1 d.append(a*(abs(l[i]-l[i+1]))) s, b = 0, 0 sm, bm = 0, 0 for i in range(n-1): s = max(d[i], s + d[i]) b = max(s, b) for i in range(1, n-1): sm = min(d[i], sm + d[i]) bm = min(sm, bm) print(max(abs(bm), abs(b)))
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.*; public class Practice { //static int a[], b[],c[]; //static long d[]; //static int m,ans; //static ArrayList<Integer> adj[]; //static int cat[]; //static boolean visited[]; static boolean b[]; public static void main(String[] args) { in=new InputReader(System.in); w=new PrintWriter(System.out); int n=in.nextInt(); long a[]=new long[n]; long b[] = new long[n-1]; long c[] = new long[n-1]; for(int i=0;i<n;i++) a[i]=in.nextLong(); for(int i=1;i<n;i++) { if(i%2!=0) { b[i-1] = Math.abs(a[i]-a[i-1]); c[i-1] = -Math.abs(a[i]-a[i-1]); } else { b[i-1] = -Math.abs(a[i]-a[i-1]); c[i-1] = Math.abs(a[i]-a[i-1]); } } long max1 =Long.MIN_VALUE,sum1=0,sum2=0,max2=Long.MIN_VALUE; for(int i=0;i<n-1;i++) { sum1 += b[i]; max1 = Math.max(sum1,max1); if(sum1<0) { sum1=0; } } // System.out.println(max1); for(int i=0;i<n-1;i++) { sum2 += c[i]; max2 = Math.max(sum2,max2); if(sum2<0) { sum2=0; } } // System.out.println(max2); w.println(Math.max(max1, max2)); w.close(); } static InputReader in; static PrintWriter w; public static void seive(long n){ b = new boolean[(int) (n+1)]; Arrays.fill(b, true); for(int i = 2;i*i<=n;i++){ if(b[i]){ for(int p = 2*i;p<=n;p+=i){ b[p] = false; } } } } static class Pair implements Comparable<Pair> { int u; int v; int z; public Pair(){ } public Pair(int u, int v,int z) { this.u = u; this.v = v; this.z = z; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31*hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return (u == other.u && v == other.v); } public int compareTo(Pair other) { return u-v; } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } static class Node2{ Node2 left = null; Node2 right = null; Node2 parent = null; int data; } //binaryStree static class BinarySearchTree{ Node2 root = null; int height = 0; int max = 0; int cnt = 1; ArrayList<Integer> parent = new ArrayList<>(); HashMap<Integer, Integer> hm = new HashMap<>(); public void insert(int x){ Node2 n = new Node2(); n.data = x; if(root==null){ root = n; } else{ Node2 temp = root,temp2 = null; while(temp!=null){ temp2 = temp; if(x>temp.data) temp = temp.right; else temp = temp.left; } if(x>temp2.data) temp2.right = n; else temp2.left = n; n.parent = temp2; parent.add(temp2.data); } } public Node2 getSomething(int x, int y, Node2 n){ if(n.data==x || n.data==y) return n; else if(n.data>x && n.data<y) return n; else if(n.data<x && n.data<y) return getSomething(x,y,n.right); else return getSomething(x,y,n.left); } public Node2 search(int x,Node2 n){ if(x==n.data){ max = Math.max(max, n.data); return n; } if(x>n.data){ max = Math.max(max, n.data); return search(x,n.right); } else{ max = Math.max(max, n.data); return search(x,n.left); } } public int getHeight(Node2 n){ if(n==null) return 0; height = 1+ Math.max(getHeight(n.left), getHeight(n.right)); return height; } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } public static String rev(String s) { StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long gcd(long a, long b) { while (b > 0) { long temp = b; b = a % b; // % is remainder a = temp; } return a; } public static long max(long x, long y, long z){ if(x>=y && x>=z) return x; if(y>=x && y>=z) return y; return z; } static int[] sieve(int n,int[] arr) { for(int i=2;i*i<=n;i++) { if(arr[i]==0) { for(int j=i*2;j<=n;j+=i) arr[j]=1; } } return arr; } 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 int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } 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
#include <bits/stdc++.h> int n; long long arr[100100]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%lld", arr + i); std::vector<long long> a; for (int i = 0; i < n - 1; i++) { a.push_back(arr[i + 1] - arr[i]); if (a[a.size() - 1] < 0) a[a.size() - 1] *= -1; } long long max = a[0], sum = a[0]; for (int i = 2; i < a.size(); i += 2) { sum += a[i] - a[i - 1]; max = std::max(max, sum); if (sum < a[i]) sum = a[i]; } if (n > 2) { sum = a[1]; max = std::max(max, sum); for (int i = 3; i < a.size(); i += 2) { sum += a[i] - a[i - 1]; max = std::max(max, sum); if (sum < a[i]) sum = a[i]; } } printf("%lld\n", max); 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 = input() a = map(int, raw_input().split()) dp = [[0, 0] for i in xrange(n)] dp[1][0] = abs(a[1] - a[0]) dp[1][1] = 0 ans = dp[1][0] for i in xrange(2, n): dp[i][0] = max(abs(a[i] - a[i - 1]), dp[i - 1][1] + abs(a[i] - a[i - 1])) dp[i][1] = max(0, dp[i - 1][0] - abs(a[i] - a[i - 1])) ans = max(ans, dp[i][0], dp[i][1]) 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 bisect import decimal from decimal import Decimal import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itertools import combinations from io import BytesIO, IOBase from itertools import accumulate # sys.setrecursionlimit(200000) # mod = 10**9+7 # mod = 998244353 decimal.getcontext().prec = 46 def primeFactors(n): prime = set() while n % 2 == 0: prime.add(2) n = n//2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: prime.add(i) n = n//i if n > 2: prime.add(n) return list(prime) def getFactors(n) : factors = [] i = 1 while i <= math.sqrt(n): if (n % i == 0) : if (n // i == i) : factors.append(i) else : factors.append(i) factors.append(n//i) i = i + 1 return factors def SieveOfEratosthenes(n): prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 num = [] for p in range(2, n+1): if prime[p]: num.append(p) return num def lcm(a,b): return (a*b)//math.gcd(a,b) def sort_dict(key_value): return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]), reverse=True) def list_input(): return list(map(int,input().split())) def num_input(): return map(int,input().split()) def string_list(): return list(input()) def decimalToBinary(n): return bin(n).replace("0b", "") def binaryToDecimal(n): return int(n,2) def DFS(n,s,adj): visited = [False for i in range(n+1)] stack = [] stack.append(s) while (len(stack)): s = stack[-1] stack.pop() if (not visited[s]): visited[s] = True for node in adj[s]: if (not visited[node]): stack.append(node) def maxSubArraySum(a,size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_ending_here < 0: max_ending_here = 0 elif (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far def solve(): n = int(input()) temp = list_input() arr1 = [] arr2 = [] c = 0 for i in range(n-1): var = abs(temp[i]-temp[i+1]) if c%2 == 0: arr1.append(var) arr2.append(-var) else: arr1.append(-var) arr2.append(var) c += 1 print(max(maxSubArraySum(arr1,n-1),maxSubArraySum(arr2,n-1))) #t = int(input()) t = 1 for _ in range(t): solve()
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.*; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static MyScanner in; static long max = -Long.MAX_VALUE, start = -1, end = -1; public static void main(String[] args) throws Exception { in = new MyScanner(); int n = in.nextInt(); int[] a = in.nextInts(n); int[] b = new int[n - 1]; for (int i = 0; i < b.length; i++) b[i] = Math.abs(a[i] - a[i + 1]); int[] c = Arrays.copyOf(b, b.length); for (int i = 0; i < c.length; i += 2) c[i] *= -1; int[] d = Arrays.copyOf(b, b.length); for (int i = 1; i < d.length; i += 2) d[i] *= -1; func(c); func(d); System.out.println(max); } static void func(int[] arr) { int s = -1; long sum = 0; for (int i = 0; i < arr.length; i++) { if (s == -1) { s = i; sum = 0; } sum += arr[i]; if (sum > max) { max = sum; start = s; end = i; } if (sum < 0) { s = -1; } } } } class MyScanner implements Closeable { public static final String CP1251 = "cp1251"; private final BufferedReader br; private StringTokenizer st; private String last; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(String path) throws IOException { br = new BufferedReader(new FileReader(path)); } public MyScanner(String path, String decoder) throws IOException { br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder)); } public void close() throws IOException { br.close(); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); last = null; return st.nextToken(); } public String next(String delim) throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); last = null; return st.nextToken(delim); } public String nextLine() throws IOException { st = null; return (last == null) ? br.readLine() : last; } public boolean hasNext() { if (st != null && st.hasMoreElements()) return true; try { while (st == null || !st.hasMoreElements()) { last = br.readLine(); st = new StringTokenizer(last); } } catch (Exception e) { return false; } return true; } public String[] nextStrings(int n) throws IOException { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = next(); return arr; } public String[] nextLines(int n) throws IOException { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = nextLine(); return arr; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextInts(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public Integer[] nextIntegers(int n) throws IOException { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public int[][] next2Ints(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextInt(); return arr; } public long nextLong() throws IOException { return Long.parseLong(next()); } public long[] nextLongs(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public long[][] next2Longs(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextLong(); return arr; } public double nextDouble() throws IOException { return Double.parseDouble(next().replace(',', '.')); } public double[] nextDoubles(int size) throws IOException { double[] arr = new double[size]; for (int i = 0; i < size; i++) arr[i] = nextDouble(); return arr; } public double[][] next2Doubles(int n, int m) throws IOException { double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextDouble(); return arr; } public boolean nextBool() throws IOException { String s = next(); if (s.equalsIgnoreCase("true") || s.equals("1")) return true; if (s.equalsIgnoreCase("false") || s.equals("0")) return false; throw new IOException("Boolean expected, String found!"); } }
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 fagain { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long m = 0; long e = 0; long o = 0; long x = sc.nextInt(); long y; long d; for (int k = 0; k < n-1; k++) { y = sc.nextInt(); if (x>y) d = x-y; else d = y-x; x = y; if (k%2 == 0) { e += d; o -= d; if (e > m) m = e; if (o < 0) o = 0; } else { e -= d; o += d; if (o > m) m = o; if (e < 0) e = 0; } } System.out.println(m); } }
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()) l=list(map(int,input().split())) arr=[] for i in range(n-1): if i%2==0: arr.append(abs(-l[i+1]+l[i])) else: arr.append(-(abs(-l[i+1]+l[i]))) arr1=[] for i in range(n-1): if i%2==1: arr1.append(abs(-l[i+1]+l[i])) else: arr1.append(-(abs(-l[i+1]+l[i]))) pre1=[arr[0]] pre2=[arr1[0]] for i in range(1,len(arr)): pre1.append(max(pre1[-1]+arr[i],arr[i])) pre2.append(max(pre2[-1]+arr1[i],arr1[i])) print(max(max(pre1),max(pre2)))
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() { int j = -1, i, x, y, n; cin >> n; long long t[n], s = 0; cin >> x; for (i = 0; i < n - 1; i++) { cin >> y; j *= -1; s += j * (abs(x - y)); t[i] = s; x = y; } sort(t, t + n - 1); if (t[0] >= 0) cout << t[n - 2]; else cout << (t[n - 2] - t[0]); 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 + 100; long long a[N], d[N], f[N][2], n, ans; int main() { scanf("%lld", &n); for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); for (int i = 1; i < n; i++) d[i] = abs(a[i] - a[i + 1]); for (int i = 1; i < n; i++) { f[i][0] = max(f[i - 1][1] + d[i], d[i]); f[i][1] = max(f[i - 1][0] - d[i], 0ll); ans = max(max(f[i][0], f[1][0]), ans); } printf("%lld\n", 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
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); // String test = "kittens"; // ConsoleIO io = new ConsoleIO(new FileReader("D:\\Comp\\GHC\\" + test + ".in"), new PrintWriter(new File("D:\\Comp\\GHC\\" + test + ".optimized"))); new Main(io).solve(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } long MOD = 1_000_000_007; int INF = Integer.MAX_VALUE / 2; List<List<Integer>> gr = new ArrayList<>(); public void solve() { int n = io.ri(); long[] vals = new long[n-1]; long prev = 0; for(int i = 0;i<n;i++) { int v = io.ri(); if (i > 0) { vals[i - 1] = prev > v ? prev - v : v - prev; } prev = v; } long[] min = new long[n-1]; long[] max = new long[n-1]; min[n-2] = vals[n-2]; max[n-2] = vals[n-2]; long res = vals[n-2]; for(int i = n-3;i>=0;i--){ min[i] = Math.min(vals[i]-max[i+1], vals[i]); max[i] = Math.max(vals[i]-min[i+1], vals[i]); res = Math.max(res, max[i]); } io.writeLine(res+""); } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} }
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.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { static void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); long[] a = new long[n]; for(int i = 0; i < n; i++) { a[i] = in.nextLong(); } long currMin = Math.abs(a[0] - a[1]); long res; long currMax = currMin, s = currMax; int minIdx = 0, maxIdx = 0; for(int i = 1; i < n - 1; i++) { s += Math.abs(a[i] - a[i + 1]) * (int)Math.pow(-1, i); if(s > currMax) { currMax = s; maxIdx = i; } if(s < currMin) { currMin = s; minIdx = i; } } if(maxIdx > minIdx) { if(currMin < 0) { res = currMax - currMin; } else { res = currMax; } } else { res = currMax; } // pocni od vtor if(n < 3) { System.out.println(res); return; } currMin = Math.abs(a[1] - a[2]); currMax = currMin; s = currMax; minIdx = maxIdx = 1; for(int i = 2; i < n - 1; i++) { s += Math.abs(a[i] - a[i + 1]) * (int)Math.pow(-1, i - 1); if(s > currMax) { currMax = s; maxIdx = i; } if(s < currMin) { currMin = s; minIdx = i; } } if(maxIdx > minIdx) { if(currMin < 0) { res = Math.max(currMax - currMin, res); } else { res = Math.max(currMax, res); } } else { res = Math.max(res, currMax); } System.out.println(res); } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } 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()); } public long nextLong() { return Long.parseLong(next()); } public long nextDouble() { 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; void MAIN(); int main() { MAIN(); return 0; } const int N = (int)1e5 + 32; int n, a[N]; long long f[N]; long long opt1, opt2, ans = -(1LL << 60); void MAIN() { scanf("%d", &n); for (int i = 0; i < (int)(n); i++) scanf("%d", a + i); for (int i = n - 2; i >= 0; i--) { f[i] = f[i + 1] + abs(a[i] - a[i + 1]) * (i % 2 == 0 ? 1 : -1); if (i % 2 == 0) ((ans) < (f[i] - opt1) ? ans = f[i] - opt1, 1 : 0); else ((ans) < (-f[i] - opt2) ? ans = -f[i] - opt2, 1 : 0); if (i % 2 == 0) { opt1 = min(opt1, f[i]); opt2 = min(opt2, -f[i]); } else { opt1 = min(opt1, f[i]); opt2 = min(opt2, -f[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; signed main() { ios::sync_with_stdio(false); cin.tie(NULL); long long n; cin >> n; vector<long long> v(n); for (long long i = 0; i < n; i++) cin >> v[i]; for (long long i = 0; i < n - 1; i++) v[i] = (i & 1) ? -(llabs(v[i] - v[i + 1])) : llabs(v[i] - v[i + 1]); long long mx = v[0], tm = 0; for (long long i = 0; i < n - 1; i++) { tm += v[i]; mx = max(mx, tm); if (tm < 0) tm = 0; } tm = 0; for (long long i = 1; i < n - 1; i++) { tm += (-v[i]); mx = max(mx, tm); if (tm < 0) tm = 0; } cout << mx; }
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
# !/bin/env python3 # encoding: UTF-8 # βœͺ H4WK3yEδΉ‘ # Mohd. Farhan Tahir # Indian Institute Of Information Technology and Management,Gwalior # Question Link # https://codeforces.com/problemset/problem/788/A # # ///==========Libraries, Constants and Functions=============/// import sys inf = float("inf") mod = 1000000007 def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline() # ///==========MAIN=============/// def main(): n = int(input()) arr = get_array() ans = 0 prefix_odd = [0]*n for i in range(n-1): prefix_odd[i] = abs(arr[i+1]-arr[i])*pow(-1, i) prefix_even = [0]*n for i in range(n-1): prefix_even[i] = abs(arr[i+1]-arr[i])*pow(-1, i+1) curr_mx, mx = prefix_odd[0], prefix_odd[0] for i in range(1, n): curr_mx = max(prefix_odd[i], prefix_odd[i]+curr_mx) mx = max(curr_mx, mx) curr_mx = prefix_even[0] for i in range(1, n): curr_mx = max(prefix_even[i], prefix_even[i]+curr_mx) mx = max(curr_mx, mx) print(mx) 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
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") bool iseven(long long int n) { if ((n & 1) == 0) return true; return false; } void print(long long int t) { cout << t; } void print(int t) { cout << t; } void print(string t) { cout << t; } void print(char t) { cout << t; } void print(double t) { cout << t; } void print(long double t) { cout << t; } template <class T, class V> void print(pair<T, V> p); template <class T> void print(vector<T> v); template <class T> void print(set<T> v); template <class T, class V> void print(map<T, V> v); template <class T> void print(multiset<T> v); template <class T, class V> void print(pair<T, V> p) { cout << "{"; print(p.first); cout << ","; print(p.second); cout << "}"; } template <class T> void print(vector<T> v) { cout << "[ "; for (T i : v) { print(i); cout << " "; } cout << "]"; } template <class T> void print(set<T> v) { cout << "[ "; for (T i : v) { print(i); cout << " "; } cout << "]"; } template <class T> void print(multiset<T> v) { cout << "[ "; for (T i : v) { print(i); cout << " "; } cout << "]"; } template <class T, class V> void print(map<T, V> v) { cout << "[ "; for (auto i : v) { print(i); cout << " "; } cout << "]"; } const long long int maxn = 1e5 + 5; long long int n; vector<long long int> a(maxn); long long int dp[maxn][2]; long long int calc(long long int ind, long long int parity, bool end) { if (end) { return 0; } if (ind == n) { return 0; } if (dp[ind][parity] != -1) { return dp[ind][parity]; } long long int ans; if (parity == 0) { ans = abs(a[ind] - a[ind + 1]) + calc(ind + 1, 1 - parity, false); } else { ans = -abs(a[ind] - a[ind + 1]) + calc(ind + 1, 1 - parity, false); } if (parity == 0) { ans = max(ans, abs(a[ind] - a[ind + 1]) + calc(ind + 1, 1 - parity, true)); } else { ans = max(ans, -abs(a[ind] - a[ind + 1]) + calc(ind + 1, 1 - parity, true)); } return dp[ind][parity] = ans; } void solve() { cin >> n; for (long long int i = 1; i <= n; ++i) { cin >> a[i]; } memset(dp, -1, sizeof(dp)); long long int ans = 0; for (long long int i = 1; i < n; ++i) { ans = max(ans, calc(i, 0, 0)); ans = max(ans, calc(i, 1, 0)); } cout << ans << '\n'; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); 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
from collections import defaultdict from sys import stdin def fun(ar): if(len(ar)) < 2: return 0 ans, cur = 0, 0 for i in range(len(ar)-1): if (i & 1) == 0 and cur < 0: cur = 0 cur += abs(ar[i+1]-ar[i])*(-1 if i & 1 else 1) ans = max(ans, cur) return ans def main(): n = int(stdin.readline()) ar = list(map(int, stdin.readline().split())) print(max(fun(ar), fun(ar[1:]))) 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())) da,p=[],1 for i in range(n-1): da.append(p*abs(a[i]-a[i+1]));p*=-1 m1,m2,s1,s2=0,0,0,0 for x in da: s1+=x if s1<0: s1=0 s2-=x if s2<0: s2=0 m1=max(m1,s1);m2=max(m2,s2) print(max(m1,m2))
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 dp[100005][3][3][3]; bool vis[100005][3][3][3]; long long arr[100005]; int n; long long best(int i, int st, int prev, int seq) { if (st > 1) return 0; if (i == n) return 0; long long& ret = dp[i][st][prev][seq]; if (vis[i][st][prev][seq] != 0) return ret; vis[i][st][prev][seq] = 1; ret = best(i, st + 1, st == 0, 0); if (st && prev && i > 0) ret = max(ret, best(i + 1, st, 1, !seq) + abs(arr[i] - arr[i - 1]) * -1 * (seq == 0 ? -1 : 1)); else if (st) ret = max(ret, best(i + 1, st, 1, seq)); else ret = max(ret, best(i + 1, 0, 0, 0)); return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cin >> n; for (int i = 0; i < n; i++) { cin >> arr[i]; } memset(dp, -1, sizeof(dp)); memset(vis, 0, sizeof(vis)); cout << best(0, 0, 0, 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; import java.util.StringTokenizer; public class C789 { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); StringTokenizer tok = new StringTokenizer(in.readLine()); int[] vals = new int[n]; int[] diff = new int[n-1]; long[] sums = new long[n-1]; vals[0] = Integer.parseInt(tok.nextToken()); long pSum = 0; long maxSum = Integer.MIN_VALUE; int maxI = 0; long minSum = Integer.MAX_VALUE; int minI = 0; for (int i = 1; i < n; i++) { vals[i] = Integer.parseInt(tok.nextToken()); diff[i-1] = vals[i] - vals[i-1]; if (diff[i-1] < 0) { diff[i-1] *= -1; } if (i%2==1) { pSum += diff[i-1]; } else { pSum -= diff[i-1]; } sums[i-1] = pSum; if (pSum > maxSum) { maxSum = pSum; maxI = i; } if (pSum < minSum) { minSum = pSum; minI = i; } //System.out.println(pSum); } //System.out.println(maxI); if (minSum < 0) { System.out.println(maxSum-minSum); } else { System.out.println(maxSum); } } }
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 functionAgain { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); long a=sc.nextLong(); long max=0; long min=0; long s=0; for(int i=1;i<n;i++) { long b=sc.nextLong(); if(i%2==0) { s+=Math.abs(a-b)*(-1); } else s+=Math.abs(a-b); max=Math.max(max, s); min=Math.min(min,s); a=b; } System.out.println(max-min); } }
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> inline T qmin(const T a, const T b) { return a < b ? a : b; } template <typename T> inline T qmax(const T a, const T b) { return a > b ? a : b; } template <typename T> inline void getmin(T &a, const T b) { if (a > b) a = b; } template <typename T> inline void getmax(T &a, const T b) { if (a < b) a = b; } inline void fileio(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } const int inf = 1e9 + 7; const long long linf = 1e17 + 7; const int N = 1e5 + 7; int tmp[N], a[N], n; long long sum[N]; priority_queue<long long, vector<long long>, greater<long long> > q; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", tmp + i); if (i == 1) continue; a[i - 1] = abs(tmp[i] - tmp[i - 1]); sum[i - 1] = sum[i - 2] + (i & 1 ? -1 : 1) * a[i - 1]; } long long ans = 0; q.push(0); for (int i = 1; i < n; ++i) { if (!(i & 1)) q.push(sum[i]); getmax(ans, sum[i] - q.top()); } while (!q.empty()) q.pop(); for (int i = 1; i < n; ++i) { sum[i] = -sum[i]; if (i & 1) q.push(sum[i]); if (q.empty()) continue; getmax(ans, sum[i] - q.top()); } printf("%I64d\n", 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
def maxSubArraySum(a, size): max_so_far = a[0] curr_max = a[0] for i in range(1, size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far, curr_max) return max_so_far n = int(input()) l = list(map(int,input().split())) o = [] p = [] m = 0 i = 0 while(i < len(l)-1): if m%2 == 0: x = 1 else: x = -1 o.append(x*(abs(l[i]-l[i+1]))) p.append(-1*x*(abs(l[i]-l[i+1]))) i = i+1 m = m+1 p.pop(0) s = maxSubArraySum(o, len(o)) if len(p) > 0: k = maxSubArraySum(p, len(p)) print(max(s, k)) else: print(s)
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> const long long mod = 1000000007L; using namespace std; long long ar[200010], t1[200010], t2[200010]; int n; long long solve(long long p[]) { long long sum = p[0]; long long ans = p[0]; for (int i = 1; i < n - 1; i++) { if (sum < 0) sum = p[i]; else sum += p[i]; ans = max(ans, sum); } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; for (int i = 0; i < n; i++) { cin >> ar[i]; } for (int i = 1; i < n; i++) { long long x = abs(ar[i] - ar[i - 1]); t1[i - 1] = x; t2[i - 1] = x; } for (int i = 0; i < n - 1; i += 2) t1[i] = -t1[i]; for (int i = 1; i < n - 1; i += 2) t2[i] = -t2[i]; long long ans = max(solve(t1), solve(t2)); 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.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; public class Main { static long INF = Long.MAX_VALUE; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] a = new int[n]; for(int i=0; i<n; ++i) { a[i] = in.nextInt(); } int i = n - 2; int sign = 1; long sum = 0; long max = -INF; while(i >= 0) { sum += sign * Math.abs(a[i] - a[i+1]); max = Math.max(max, sum); if(sum < 0) sum = 0; sign *= -1; i--; } i = n - 3; sign = 1; sum = 0; while(i >= 0) { sum += sign * Math.abs(a[i] - a[i+1]); max = Math.max(max, sum); if(sum < 0) sum = 0; sign *= -1; i--; } System.out.println(max); out.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { 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 = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { 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 { res *= 10; res += c - '0'; c = read(); } 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 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 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private 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
#include <bits/stdc++.h> using namespace std; using namespace std::chrono; template <typename A> ostream &operator<<(ostream &cout, vector<A> const &v); template <typename A, typename B> ostream &operator<<(ostream &cout, pair<A, B> const &p) { return cout << "(" << p.first << ", " << p.second << ")"; } template <typename A> ostream &operator<<(ostream &cout, vector<A> const &v) { cout << "["; for (int i = 0; i < v.size(); i++) { if (i) cout << ", "; cout << v[i]; } return cout << "]"; } template <typename A, typename B> istream &operator>>(istream &cin, pair<A, B> &p) { cin >> p.first; return cin >> p.second; } mt19937 rng(steady_clock::now().time_since_epoch().count()); void usaco(string filename) { freopen((filename + ".in").c_str(), "r", stdin); freopen((filename + ".out").c_str(), "w", stdout); } const long double pi = 3.14159265358979323846; long long n, m, k, q, l, r, x, y, z; long long a[1000005]; long long b[1000005]; long long c[1000005]; string second, t; long long ans = 0; long long solve2() { long long r = 0, best = 0; for (long long i = 0; i < (n - 1); ++i) { r += b[i]; best = max(best, r); if (r < 0) r = 0; } return best; } void solve(int tc) { cin >> n; for (int ele = 0; ele < n; ele++) cin >> a[ele]; ; for (long long i = 0; i < (n - 1); ++i) { b[i] = abs(a[i] - a[i + 1]); if (i % 2) b[i] = -b[i]; } ans = 0; ans = max(ans, solve2()); for (long long i = 0; i < (n - 1); ++i) b[i] = -b[i]; ans = max(ans, solve2()); cout << ans << '\n'; } int main() { { ios_base::sync_with_stdio(false); } { cin.tie(NULL); cout.tie(NULL); } int tc = 1; for (int t = 0; t < tc; t++) solve(t); }
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 arr[100010]; int n; long long asol[100010]; long long nokol[100010]; int main() { cin >> n; for (int i = 0; i <= n - 1; i++) { scanf("%I64d", &arr[i]); } for (int i = 0; i <= n - 2; i++) { asol[i] = abs(arr[i + 1] - arr[i]); nokol[i] = asol[i]; if (i & 1) asol[i] *= -1; else nokol[i] *= -1; } long long sum = 0; long long mx = 0; for (int i = 0; i <= n - 2; i++) { sum += asol[i]; if (sum > mx) mx = sum; if (sum < 0) sum = 0; } sum = 0; for (int i = 0; i <= n - 2; i++) { sum += nokol[i]; if (sum > mx) mx = sum; if (sum < 0) sum = 0; } cout << mx << 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; long long ma, mi, ans, s[500001], a[500001]; int n; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); long long ma = -1e9, mi = 1e9; for (int i = 2; i <= n; i++) { s[i] = s[i - 1] + abs(a[i] - a[i - 1]) * (i & 1 ? -1 : 1); ma = max(ma, s[i]); mi = min(mi, s[i]); } ans = ma - min(0LL, mi); printf("%I64d", 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.util.Scanner; /** * Created by lenovo on 1/29/2018. */ public class M788A { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] input = new int[n]; for (int i = 0; i < n; ++ i) { input[i] = scanner.nextInt(); } int[] abs = new int[n]; for (int i = 0; i < n - 1; ++ i) { abs[i] = Math.abs(input[i] - input[i + 1]); } if (n == 2) { System.out.println(abs[0]); return; } long answer = abs[0]; long sumWhenEven = 0; long sumWhenOdd = 0; for (int i = 0; i < n - 1; ++ i) { if (sumWhenEven < 0){ sumWhenEven = 0; } if (sumWhenOdd < 0) { sumWhenOdd = 0; } if (i % 2 == 0) { sumWhenEven += abs[i]; sumWhenOdd -= abs[i]; answer = Math.max(answer, sumWhenEven); } else { sumWhenEven -= abs[i]; sumWhenOdd += abs[i]; answer = Math.max(answer, sumWhenOdd); } } System.out.println(answer); } }
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.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class Main { private static FastReader fastReader = new FastReader(); private static FastWriter fastWriter = new FastWriter(); private static long mod = ((long) 1e9) + 7; public static void main(String[] args) throws IOException { int n = fastReader.readInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = fastReader.readInt(); } long dp[][] = new long[n + 1][2]; long ans = -1; for (int i = 1; i < n; i++) { long cur = Math.abs(arr[i] - arr[i - 1]); if (i == 1) dp[i][1] = 0; else dp[i][1] = dp[i - 1][0] - cur; dp[i][0] = cur + Math.max(0, dp[i - 1][1]); ans = Math.max(ans, Math.max(dp[i][0], dp[i][1])); } fastWriter.println(ans); } static class FastReader { private BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; public String read() throws IOException { if (null == stringTokenizer || !stringTokenizer.hasMoreElements()) stringTokenizer = new StringTokenizer(bufferedReader.readLine().trim()); return stringTokenizer.nextToken(); } public int readInt() throws IOException { return Integer.parseInt(read()); } public long readLong() throws IOException { return Long.parseLong(read()); } } static class FastWriter { private BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out)); public <T> void print(T object) throws IOException { bufferedWriter.write(object.toString()); bufferedWriter.flush(); } public <T> void println(T object) throws IOException { print(object.toString() + "\n"); } } }
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.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; public class solve { public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); 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(); long x[]=new long[n-1]; for(int i=0;i<n-1;i++) x[i]=Math.abs((a[i])-(a[i+1])); long sum1=0; long sum2=0; long ans1=0; long ans2=0; long ANS =-1111111; for(int i=0;i<x.length;i++) { long tmp; if(i%2==0){ tmp= x[i]*1; }else tmp =x[i]*-1; sum1+=tmp; if(sum1<0)sum1=0; ans1=Math.max(ans1, sum1); if(i>=1 ) { if(i%2!=0) tmp=x[i]*1; else tmp=x[i]*-1; sum2+=tmp; if(sum2<0)sum2=0; ans2=Math.max(ans2, sum2); } ANS=Math.max(ANS, Math.max(ans1, ans2)); } System.out.println(ANS); } } class pair implements Comparable{ int x ,y,z; pair(int x,int y,int z) { this.x=x; this.y=y; this.z=z; } @Override public int compareTo(Object arg0) { pair u =((pair)arg0); return -this.z+u.z; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { 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
#include <bits/stdc++.h> using namespace std; void _print(long long int t) { cerr << t; } void _print(string t) { cerr << t; } void _print(char t) { cerr << t; } void _print(long double t) { cerr << t; } void _print(double t) { cerr << t; } void _print(unsigned long long t) { cerr << t; } template <class T, class V> void _print(pair<T, V> p); template <class T> void _print(vector<T> v); template <class T> void _print(set<T> v); template <class T, class V> void _print(map<T, V> v); template <class T> void _print(multiset<T> v); template <class T, class V> void _print(pair<T, V> p) { cerr << "{"; _print(p.first); cerr << ","; _print(p.second); cerr << "}"; } template <class T> void _print(vector<T> v) { cerr << "[ "; for (T i : v) { _print(i); cerr << " "; } cerr << "]"; } template <class T> void _print(set<T> v) { cerr << "[ "; for (T i : v) { _print(i); cerr << " "; } cerr << "]"; } template <class T> void _print(multiset<T> v) { cerr << "[ "; for (T i : v) { _print(i); cerr << " "; } cerr << "]"; } template <class T, class V> void _print(map<T, V> v) { cerr << "[ "; for (auto i : v) { _print(i); cerr << " "; } cerr << "]"; } template <class T> T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); } template <class T> T lcm(T a, T b) { return (a * b) / __gcd(a, b); } template <class T> T ceil(T numerator, T denominator) { return (numerator + denominator - 1) / denominator; } template <class T> bool isPrime(T N) { for (T i = 2; i * i <= N; ++i) { if (N % i == 0) return false; } return true; } template <class T> T cbrt(T x) { T lo = 1, hi = min(2000000ll, x); while (hi - lo > 1) { T mid = (lo + hi) / 2; if (mid * mid * mid < x) { lo = mid; } else hi = mid; } if (hi * hi * hi <= x) return hi; else return lo; } template <class T> T sqrt(T target) { T l = 1, r = target; while (r > l + 1) { T m = (l + r) / 2; if (m * m <= target) l = m; else r = m; } return l; } long long int bin_power(long long int a, long long int b, long long int mod) { long long int res = 1; while (b > 0) { if (b & 1) res = (res * a) % mod; a = (a * a) % mod; b = b >> 1; } return res; } long long int mod_inv(long long int a, long long int b) { return bin_power(a, b - 2, b); } long long int mod_add(long long int a, long long int b, long long int m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } long long int mod_mul(long long int a, long long int b, long long int m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } long long int mod_sub(long long int a, long long int b, long long int m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } long long int mod_div(long long int a, long long int b, long long int m) { a = a % m; b = b % m; return (mod_mul(a, mod_inv(b, m), m) + m) % m; } const long long int mod = 1000000007; const long long int N = 1e5 + 5; long long int n, a[N]; long long int kadane(long long int parity) { long long int cur_sum = 0, ans = -1e16; for (long long int i = 0; i < n - 1; i++) { if (i % 2 == parity) cur_sum += abs(a[i] - a[i + 1]); else cur_sum -= abs(a[i] - a[i + 1]); ans = max(ans, cur_sum); cur_sum = max(cur_sum, 0ll); } return ans; } void solve() { cin >> n; for (long long int i = 0; i < n; i++) cin >> a[i]; long long int ans = max(kadane(0), kadane(1)); cout << ans << '\n'; return; } int32_t main() { ios_base::sync_with_stdio(0), cin.tie(0); solve(); }
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
def getNum(): inp = input() return int(inp) def getArrNum(): inp = input() A = [int(x) for x in inp.split(' ')] return A def getMaximal(arr): best = 0 curBest = 0 for x in arr: if curBest>=0: curBest += x else: curBest = x best = max(best,curBest) return best if __name__=='__main__': N = getNum() arr = getArrNum() odd = [] even = [] for i in range(N-1): nm = abs(arr[i]-arr[i+1]) neg = nm*-1 if i%2==0: odd.append(nm) even.append(neg) else: odd.append(neg) even.append(nm) ans = max(getMaximal(odd),getMaximal(even)) 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; const int N = 1e5 + 5; int a[N]; int main() { ios_base ::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; for (int i = 0; i < n; ++i) cin >> a[i]; long long sum = 0; long long maxSum = -1e14; for (int i = 0; i + 1 < n; i++) { if (i % 2 == 0) { sum += abs(a[i] - a[i + 1]); maxSum = max(maxSum, sum); } else { sum += -abs(a[i] - a[i + 1]); sum = max(sum, 0ll); } } sum = 0; for (int i = 1; i + 1 < n; i++) { if (i & 1) { sum += abs(a[i] - a[i + 1]); maxSum = max(maxSum, sum); } else { sum += -abs(a[i] - a[i + 1]); sum = max(sum, 0ll); } } cout << maxSum; }
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; void solve() { int n; cin >> n; vector<long long> a(n); for (auto &it : a) cin >> it; ; long long ans = -1e18, sum = 0; for (int i = 0; i < n - 1; i++) { if (i % 2 == 0) { sum += abs(a[i] - a[i + 1]); } else { sum -= abs(a[i] - a[i + 1]); } if (sum <= 0) { sum = 0; } ans = max(ans, sum); } sum = 0; for (int i = 1; i < n - 1; i++) { if (i % 2 == 1) { sum += abs(a[i] - a[i + 1]); } else { sum -= abs(a[i] - a[i + 1]); } if (sum <= 0) { sum = 0; } ans = max(ans, sum); } cout << ans << '\n'; } int main() { solve(); }
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 dp[100005][2]; int main() { int n; while (cin >> n) { memset(dp, 0, sizeof(dp)); for (int i = 1; i <= n; i++) cin >> a[i]; int x = 1; for (int i = 2; i <= n; i++) { dp[i][0] = dp[i - 1][0] + x * abs(a[i] - a[i - 1]); x *= -1; } x = 1; for (int i = 3; i <= n; i++) { dp[i][1] = dp[i - 1][1] + x * abs(a[i] - a[i - 1]); x *= -1; } long long ans = 0, mn = 0; for (int i = 2; i <= n; i++) { mn = min(mn, dp[i][0]); ans = max(ans, dp[i][0] - mn); } mn = 0; for (int i = 3; i <= n; i++) { mn = min(mn, dp[i][1]); ans = max(ans, dp[i][1] - mn); } 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
def maxSubArray( A): if not A: return 0 curSum = maxSum = A[0] for num in A[1:]: curSum = max(num, curSum + num) maxSum = max(maxSum, curSum) return maxSum n = int(input()) L = list(map(int, input().split())) D1 = [] D2 = [] for i in range(1, len(L)): D1.append(abs(L[i] - L[i-1]) * (-1)**i) D2.append(abs(L[i] - L[i-1]) * (-1)**(i+1)) print(max(maxSubArray(D1), maxSubArray(D2)))
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.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) throws IOException { IO io = new IO(); int n = io.getInt(); long ans = 0; List<Integer> ls = io.getIntegerArray(n); long[] diff = new long[n], max = new long[n], min = new long[n]; for(int i = 0; i < n - 1; i++) diff[i] = Math.abs(ls.get(i) - ls.get(i + 1)); min[n - 1] = max[n - 1] = 0; for(int i = n - 2; i >= 0; i--){ min[i] = Math.min(diff[i], diff[i] - max[i + 1]); max[i] = Math.max(diff[i], diff[i] - min[i + 1]); ans = Math.max(ans, max[i]); } System.out.println(ans); } } class Utils { static int[][] fourDirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; static int[][] eightDirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; static int modAdd(int a, int b) { return (int) ((a + (long) b) % 1000000007); } static int modSub(int a, int b) { return (int) ((a - (long) b + 1000000007) % 1000000007); } public static List<Integer> sieve(int n) { boolean b[] = new boolean[n + 1]; List<Integer> ans = new ArrayList<>(); Arrays.fill(b, true); for (int i = 2; i <= n; i++) { if (b[i]) { ans.add(i); for (int j = i * i; j >= 0 && j <= n; j += i) { b[j] = false; } } } return ans; } public static boolean isPrime(long n) { long sqrt = (long) Math.sqrt(n); for (int i = 2; i <= sqrt; i++) { if (n % i == 0) return false; } return true; } public static long mod(long n) { if (n > 0) return n % 1000000007; return (n + 2000000014) % 1000000007; } public static boolean isSqr(long n) { int sqrt = (int) Math.sqrt(n); return n == (long) sqrt * sqrt; } public static boolean inRange(long i, long l, long h) { return i >= l && i <= h; } public static boolean isValid(int i, int j, int n, int m) { return i >= 0 && j >= 0 && i < n && j < m; } public static void swap(List<Integer> ls, int i, int j) { int temp = ls.get(i); ls.set(i, ls.get(j)); ls.set(j, temp); } public static long gcd(long a, long b) { if (a < b) return gcd(b, a); else if (a == b || b == 0) return a; else { return gcd(b, a % b); } } public static long subSum(long[] pre, int l, int h) { return l == 0 ? pre[h] : pre[h] - pre[l - 1]; } public static void ifPrint(boolean test, Object ifValue, Object elseValue) { System.out.println(test ? ifValue : elseValue); } public static void print(Character delim, Object... a) { List<String> top = new ArrayList<>(); for (Object aa : a) top.add(aa == null ? "null" : aa.toString()); System.out.println(join(top, delim.toString())); } public static void print(Object... a) { print(' ', a); } public static <T extends Comparable<T>> int lowerBound(T[] arr, int l, int h, T key) { while (l < h) { int mid = (l + h) / 2; if (arr[mid].compareTo(key) < 0) l = mid + 1; else h = mid; } return arr[l].compareTo(key) >= 0 ? l : -1; } public static <T extends Comparable<T>> int upperBound(T[] arr, int l, int h, T key) { while (l < h) { int mid = (l + h) / 2; if (arr[mid].compareTo(key) < 0) l = mid + 1; else if (arr[mid].compareTo(key) == 0) l = mid; else h = mid; if (h == l + 1) break; } return arr[l].compareTo(key) >= 0 ? l : -1; } public static <T> String join(List<T> ls) { return join(ls, " "); } public static <T> String join(List<T> ls, String delim) { StringJoiner sj = new StringJoiner(delim); for (T a : ls) sj.add(a.toString()); return sj.toString(); } public static <T> void print2DArray(List<List<T>> mat) { for (List<T> m : mat) { System.out.println("{ " + join(m, ", ") + " }"); } } public static <T> void reverseArrray(T[] arr, int l, int h) { while (l < h) { T temp = arr[l]; arr[l] = arr[h]; arr[h] = temp; l++; h--; } } } class IO { private BufferedReader br = null; private StringTokenizer st = null; public IO() { this(System.in); } public IO(InputStream is) { this.br = new BufferedReader(new InputStreamReader(is)); } public List<String> getStringArray(int n) throws IOException { if (n == 0) return new ArrayList<>(); if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); List<String> res = new ArrayList<>(); for (int i = 0; i < n; i++) { if (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); res.add(st.nextToken()); } return res; } public String getString() throws IOException { List<String> res = this.getStringArray(1); return res.size() == 0 ? "" : res.get(0); } public List<Integer> getIntegerArray(int n) throws IOException { if (n == 0) return new ArrayList<>(); List<String> res = getStringArray(n); return res.stream().map(Integer::parseInt).collect(Collectors.toList()); } public Integer getInt() throws IOException { List<Integer> res = this.getIntegerArray(1); return res.size() == 0 ? 0 : res.get(0); } public List<Long> getLongArray(int n) throws IOException { if (n == 0) return new ArrayList<>(); List<String> res = getStringArray(n); return res.stream().map(Long::parseLong).collect(Collectors.toList()); } public Long getLong() throws IOException { List<Long> res = this.getLongArray(1); return res.size() == 0 ? 0L : res.get(0); } public List<Double> getDoubleArray(int n) throws IOException { if (n == 0) return new ArrayList<>(); List<String> res = getStringArray(n); return res.stream().map(Double::parseDouble).collect(Collectors.toList()); } public Double getDouble() throws IOException { List<Double> res = this.getDoubleArray(1); return res.size() == 0 ? 0.0 : res.get(0); } }
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(arr): max_ending_here = 0 max_so_far = 0 for i in arr: max_ending_here += i if max_ending_here < 0: max_ending_here = 0 if max_so_far < max_ending_here: max_so_far = max_ending_here return max_so_far n = int(raw_input()) array = map(int ,raw_input().split()) fun = [] for i in xrange(len(array)-1): fun.append(abs(array[i] - array[i+1])) nuf = fun[:] for i in xrange(0, len(fun), 2): fun[i] *= -1 for i in xrange(1, len(nuf), 2): nuf[i] *= -1 print max(kadane(fun), kadane(nuf))
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> using namespace std; long long a[100005], b[100005], c[100005]; int main() { long long n; cin >> n; for (long long i = 0; i < n; i++) cin >> a[i]; long long maxi = 0, mini = 0, res = 0; for (long long i = 0; i < n - 1; i++) { long long x = abs(a[i] - a[i + 1]); long long miniaux = min(0LL, x - maxi); long long maxiaux = max(0LL, x - mini); mini = miniaux; maxi = maxiaux; res = max(res, maxi); } cout << res << 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; int a[100005], b[100005], c[100005]; long long maxsum(int x[], int s) { long long m = 0; long long l = 0; for (int i = 0; i < s; i++) { l = l + 1ll * x[i]; if (l > m) m = l; if (l < 0) l = 0; } return m; } int main() { int n, i; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &a[i]); } for (i = 0; i < n - 1; i++) { if (i % 2 == 0) { b[i] = abs(a[i] - a[i + 1]); } else b[i] = -1 * abs(a[i] - a[i + 1]); } for (i = 1; i < n - 1; i++) { if (i % 2 != 0) { c[i - 1] = abs(a[i] - a[i + 1]); } else c[i - 1] = -1 * abs(a[i] - a[i + 1]); } long long m1 = maxsum(b, n - 1); long long m2 = maxsum(c, n - 2); cout << max(m1, m2); 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())) dif = list() for i in range(n-1): if(i%2==0): dif.append(int(abs(a[i] - a[i+1]))) else: dif.append(-1 * int(abs(a[i] - a[i+1]))) #print('dif = ', dif) pref = list() for i in range(len(dif)): if(i==0): pref.append(dif[0]) else: pref.append(pref[i-1] + dif[i]) #print('pref = ', pref) mx = 0 mn = 0 mxidx = 0 mnidx = 0 for i in range(len(pref)): if(pref[i] > mx): mx = pref[i] mxidx = i if(pref[i] < mn): mn = pref[i] mnidx = i print(mx-mn)
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 a[(int)1e5 + 30], b[(int)1e5 + 30], dp[(int)1e5 + 30], dp2[(int)1e5 + 30]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 1; i < n; i++) { b[i] = abs(a[i] - a[i - 1]); } long long ans = -1, res = 0; for (int i = 1; i < n; i++) { if (i % 2) res += b[i]; else res -= b[i]; if (res < 0) res = 0; ans = max(ans, res); } res = 0; for (int i = 2; i < n; i++) { if (i % 2) res -= b[i]; else res += b[i]; if (res < 0) res = 0; ans = max(ans, res); } 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
n = int(input()) a = list(map(int, input().split())) b = [0] * n c = [0] * n for i in range(n - 1): x = abs(a[i] - a[i + 1]) if i % 2 == 0: b[i] = x c[i] = -x else: b[i] = -x c[i] = x def maxSubArray(arr): best = 0 current = 0 for x in arr: current = max(0, current + x) best = max(best, current) return best print(max(maxSubArray(c), maxSubArray(b)))
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 from collections import Counter #sys.stdin = open('input.txt', 'r') #sys.stdout = open('output.txt','w') N = int(raw_input().strip()) A = map(int, raw_input().strip().split(' ')) A = [abs(A[i]-A[i+1]) for i in xrange(N-1)] dpplus = [0]*(N-1) dpminus = [0]*(N-1) dpplus[0],dpminus[0] = A[0],-A[0] for i in xrange(1,N-1) : dpplus[i] = max(A[i],dpminus[i-1]+A[i]) dpminus[i] = max(-A[i],dpplus[i-1]-A[i]) print max(max(dpplus), max(dpminus))
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
c = lambda:map(int, raw_input().split()) n = input() a = c() b, c = [0], 1 for i in range(1, n): b.append(abs(a[i] - a[i - 1]) * c) c = -c x, y, s, m = 0, 0, 0, 0 for i in range(1, n): s += b[i] x = min(x, s) y = max(y, s) m = max(m, y - x) print m
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> using namespace std; long long kadane(vector<long long> &a) { long long max_sum = INT_MIN, curr_sum = 0; for (long long i = 0; i < (long long)a.size(); i++) { curr_sum += a[i]; if (curr_sum < 0) curr_sum = 0; max_sum = max(max_sum, curr_sum); } return max_sum; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ; long long n; cin >> n; vector<long long> a(n); for (long long i = 0; i < n; i++) { cin >> a[i]; } vector<long long> diff(n - 1); for (long long i = 0; i < n - 1; i++) { diff[i] = abs(a[i] - a[i + 1]); } vector<long long> odd_negative(n - 1), even_negative(n - 1); for (long long i = 0; i < n - 1; i++) { if (i % 2 == 0) odd_negative[i] = diff[i], even_negative[i] = -1 * diff[i]; else odd_negative[i] = -1 * diff[i], even_negative[i] = diff[i]; } cout << max(kadane(even_negative), kadane(odd_negative)) << "\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 main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; long long n, a[100005], b[100005], c[100005]; cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; b[0] = 0, c[0] = 0; for (int i = 1; i < n; i++) { if (i % 2 == 0) b[i] = b[i - 1] + (abs(a[i] - a[i + 1])); else b[i] = b[i - 1] - (abs(a[i] - a[i + 1])); if (i % 2 == 0) c[i] = c[i - 1] - (abs(a[i] - a[i + 1])); else c[i] = c[i - 1] + (abs(a[i] - a[i + 1])); } long long prefb = 0, prefc = 0, mb = 0, mc = 0, ans = -2e9; for (int i = 1; i < n; i++) { if (i % 2) mb = min(mb, b[i]); else mc = min(mc, c[i]); ans = max(ans, max(b[i] - mb, c[i] - mc)); } 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
//package baobab; import java.io.*; import java.util.*; public class C { public static void main(String[] args) { HashSet<Long> bad = new HashSet<>(); Solver solver = new Solver(); } static class Solver { IO io; public Solver() { this.io = new IO(); try { solve(); } finally { io.close(); } } /****************************** START READING HERE ********************************/ void solve() { int n = io.nextInt(); int[] a = new int[n]; for (int i=0; i<n; i++) { a[i] = io.nextInt(); } long max = -Long.MAX_VALUE; long curr = 0; for (int i=0; i<n-1; i++) { long val = Math.abs(a[i] - a[i+1]) * (i%2==0 ? 1 : -1); curr += val; max = Math.max(max, curr); if (curr < 0 && i%2!=0) { curr = 0; } } curr = 0; for (int i=1; i<n-1; i++) { long val = Math.abs(a[i] - a[i+1]) * (i%2==0 ? -1 : 1); curr += val; max = Math.max(max, curr); if (curr < 0 && i%2==0) { curr = 0; } } io.println(max); } /************************** UTILITY CODE BELOW THIS LINE **************************/ long MOD = (long)1e9 + 7; List<Integer>[] toGraph(IO io, int n) { List<Integer>[] g = new ArrayList[n+1]; for (int i=1; i<=n; i++) g[i] = new ArrayList<>(); for (int i=1; i<=n-1; i++) { int a = io.nextInt(); int b = io.nextInt(); g[a].add(b); g[b].add(a); } return g; } class Point { int y; int x; public Point(int y, int x) { this.y = y; this.x = x; } } class IDval implements Comparable<IDval> { int id; long val; public IDval(int id, long val) { this.val = val; this.id = id; } @Override public int compareTo(IDval o) { if (this.val < o.val) return -1; if (this.val > o.val) return 1; return this.id - o.id; } } long pow(long base, int exp) { if (exp == 0) return 1L; long x = pow(base, exp/2); long ans = x * x; if (exp % 2 != 0) ans *= base; return ans; } long gcd(long... v) { /** Chained calls to Euclidean algorithm. */ if (v.length == 1) return v[0]; long ans = gcd(v[1], v[0]); for (int i=2; i<v.length; i++) { ans = gcd(ans, v[i]); } return ans; } long gcd(long a, long b) { /** Euclidean algorithm. */ if (b == 0) return a; return gcd(b, a%b); } int[] generatePrimesUpTo(int last) { /* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */ int[] div = new int[last+1]; for (int x=2; x<=last; x++) { if (div[x] > 0) continue; for (int u=2*x; u<=last; u+=x) { div[u] = x; } } return div; } long lcm(long a, long b) { /** Least common multiple */ return a * b / gcd(a,b); } private class ElementCounter { private HashMap<Long, Integer> elements; public ElementCounter() { elements = new HashMap<>(); } public void add(long element) { int count = 1; if (elements.containsKey(element)) count += elements.get(element); elements.put(element, count); } public void remove(long element) { int count = elements.get(element); count--; if (count == 0) elements.remove(element); else elements.put(element, count); } public int get(long element) { if (!elements.containsKey(element)) return 0; return elements.get(element); } public int size() { return elements.size(); } } class StringCounter { HashMap<String, Long> elements; public StringCounter() { elements = new HashMap<>(); } public void add(String identifier) { long count = 1; if (elements.containsKey(identifier)) count += elements.get(identifier); elements.put(identifier, count); } public void remove(String identifier) { long count = elements.get(identifier); count--; if (count == 0) elements.remove(identifier); else elements.put(identifier, count); } public long get(String identifier) { if (!elements.containsKey(identifier)) return 0; return elements.get(identifier); } public int size() { return elements.size(); } } class DisjointSet { /** Union Find / Disjoint Set data structure. */ int[] size; int[] parent; int componentCount; public DisjointSet(int n) { componentCount = n; size = new int[n]; parent = new int[n]; for (int i=0; i<n; i++) parent[i] = i; for (int i=0; i<n; i++) size[i] = 1; } public void join(int a, int b) { /* Find roots */ int rootA = parent[a]; int rootB = parent[b]; while (rootA != parent[rootA]) rootA = parent[rootA]; while (rootB != parent[rootB]) rootB = parent[rootB]; if (rootA == rootB) { /* Already in the same set */ return; } /* Merge smaller set into larger set. */ if (size[rootA] > size[rootB]) { size[rootA] += size[rootB]; parent[rootB] = rootA; } else { size[rootB] += size[rootA]; parent[rootA] = rootB; } componentCount--; } } class LCAFinder { /* O(n log n) Initialize: new LCAFinder(graph) * O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */ int[] nodes; int[] depths; int[] entries; int pointer; FenwickMin fenwick; public LCAFinder(List<Integer>[] graph) { this.nodes = new int[(int)10e6]; this.depths = new int[(int)10e6]; this.entries = new int[graph.length]; this.pointer = 1; boolean[] visited = new boolean[graph.length+1]; dfs(1, 0, graph, visited); fenwick = new FenwickMin(pointer-1); for (int i=1; i<pointer; i++) { fenwick.set(i, depths[i] * 1000000L + i); } } private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) { visited[node] = true; entries[node] = pointer; nodes[pointer] = node; depths[pointer] = depth; pointer++; for (int neighbor : graph[node]) { if (visited[neighbor]) continue; dfs(neighbor, depth+1, graph, visited); nodes[pointer] = node; depths[pointer] = depth; pointer++; } } public int find(int a, int b) { int left = entries[a]; int right = entries[b]; if (left > right) { int temp = left; left = right; right = temp; } long mixedBag = fenwick.getMin(left, right); int index = (int) (mixedBag % 1000000L); return nodes[index]; } } class FenwickMin { long n; long[] original; long[] bottomUp; long[] topDown; public FenwickMin(int n) { this.n = n; original = new long[n+2]; bottomUp = new long[n+2]; topDown = new long[n+2]; } public void set(int modifiedNode, long value) { long replaced = original[modifiedNode]; original[modifiedNode] = value; // Update left tree int i = modifiedNode; long v = value; while (i <= n) { if (v > bottomUp[i]) { if (replaced == bottomUp[i]) { v = Math.min(v, original[i]); for (int r=1 ;; r++) { int x = (i&-i)>>>r; if (x == 0) break; int child = i-x; v = Math.min(v, bottomUp[child]); } } else break; } if (v == bottomUp[i]) break; bottomUp[i] = v; i += (i&-i); } // Update right tree i = modifiedNode; v = value; while (i > 0) { if (v > topDown[i]) { if (replaced == topDown[i]) { v = Math.min(v, original[i]); for (int r=1 ;; r++) { int x = (i&-i)>>>r; if (x == 0) break; int child = i+x; if (child > n+1) break; v = Math.min(v, topDown[child]); } } else break; } if (v == topDown[i]) break; topDown[i] = v; i -= (i&-i); } } public long getMin(int a, int b) { long min = original[a]; int prev = a; int curr = prev + (prev&-prev); // parent right hand side while (curr <= b) { min = Math.min(min, topDown[prev]); // value from the other tree prev = curr; curr = prev + (prev&-prev);; } min = Math.min(min, original[prev]); prev = b; curr = prev - (prev&-prev); // parent left hand side while (curr >= a) { min = Math.min(min,bottomUp[prev]); // value from the other tree prev = curr; curr = prev - (prev&-prev); } return min; } } class FenwickSum { public long[] d; public FenwickSum(int n) { d=new long[n+1]; } /** a[0] must be unused. */ public FenwickSum(long[] a) { d=new long[a.length]; for (int i=1; i<a.length; i++) { modify(i, a[i]); } } /** Do not modify i=0. */ void modify(int i, long v) { while (i<d.length) { d[i] += v; // Move to next uplink on the RIGHT side of i i += (i&-i); } } /** Returns sum from a to b, *BOTH* inclusive. */ long getSum(int a, int b) { return getSum(b) - getSum(a-1); } private long getSum(int i) { long sum = 0; while (i>0) { sum += d[i]; // Move to next uplink on the LEFT side of i i -= (i&-i); } return sum; } } class SegmentTree { /** Query sums with log(n) modifyRange */ int N; long[] p; public SegmentTree(int n) { /* TODO: Test that this works. */ N = n; p = new long[2*N]; } public void modifyRange(int a, int b, long change) { muuta(a, change); muuta(b+1, -change); } void muuta(int k, long muutos) { k += N; p[k] += muutos; for (k /= 2; k >= 1; k /= 2) { p[k] = p[2*k] + p[2*k+1]; } } public long get(int k) { int a = N; int b = k+N; long s = 0; while (a <= b) { if (a%2 == 1) s += p[a++]; if (b%2 == 0) s += p[b--]; a /= 2; b /= 2; } return s; } } class Zalgo { public int pisinEsiintyma(String haku, String kohde) { char[] s = new char[haku.length() + 1 + kohde.length()]; for (int i=0; i<haku.length(); i++) { s[i] = haku.charAt(i); } int j = haku.length(); s[j++] = '#'; for (int i=0; i<kohde.length(); i++) { s[j++] = kohde.charAt(i); } int[] z = toZarray(s); int max = 0; for (int i=haku.length(); i<z.length; i++) { max = Math.max(max, z[i]); } return max; } public int[] toZarray(char[] s) { int n = s.length; int[] z = new int[n]; int a = 0, b = 0; for (int i = 1; i < n; i++) { if (i > b) { for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++; } else { z[i] = z[i - a]; if (i + z[i - a] > b) { for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++; a = i; b = i + z[i] - 1; } } } return z; } public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) { // this is alternative use case char[] s = new char[haku.length() + 1 + kohde.length()]; for (int i=0; i<haku.length(); i++) { s[i] = haku.charAt(i); } int j = haku.length(); s[j++] = '#'; for (int i=0; i<kohde.length(); i++) { s[j++] = kohde.charAt(i); } int[] z = toZarray(s); List<Integer> indexes = new ArrayList<>(); for (int i=haku.length(); i<z.length; i++) { if (z[i] < haku.length()) continue; indexes.add(i); } return indexes; } } class StringHasher { class HashedString { long[] hashes; long[] modifiers; public HashedString(long[] hashes, long[] modifiers) { this.hashes = hashes; this.modifiers = modifiers; } } long P; long M; public StringHasher() { initializePandM(); } HashedString hashString(String s) { int n = s.length(); long[] hashes = new long[n]; long[] modifiers = new long[n]; hashes[0] = s.charAt(0); modifiers[0] = 1; for (int i=1; i<n; i++) { hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M; modifiers[i] = (modifiers[i-1] * P) % M; } return new HashedString(hashes, modifiers); } /** * Indices are inclusive. */ long getHash(HashedString hashedString, int startIndex, int endIndex) { long[] hashes = hashedString.hashes; long[] modifiers = hashedString.modifiers; long result = hashes[endIndex]; if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M; if (result < 0) result += M; return result; } // Less interesting methods below /** * Efficient for 2 input parameter strings in particular. */ HashedString[] hashString(String first, String second) { HashedString[] array = new HashedString[2]; int n = first.length(); long[] modifiers = new long[n]; modifiers[0] = 1; long[] firstHashes = new long[n]; firstHashes[0] = first.charAt(0); array[0] = new HashedString(firstHashes, modifiers); long[] secondHashes = new long[n]; secondHashes[0] = second.charAt(0); array[1] = new HashedString(secondHashes, modifiers); for (int i=1; i<n; i++) { modifiers[i] = (modifiers[i-1] * P) % M; firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M; secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M; } return array; } /** * Efficient for 3+ strings * More efficient than multiple hashString calls IF strings are same length. */ HashedString[] hashString(String... strings) { HashedString[] array = new HashedString[strings.length]; int n = strings[0].length(); long[] modifiers = new long[n]; modifiers[0] = 1; for (int j=0; j<strings.length; j++) { // if all strings are not same length, defer work to another method if (strings[j].length() != n) { for (int i=0; i<n; i++) { array[i] = hashString(strings[i]); } return array; } // otherwise initialize stuff long[] hashes = new long[n]; hashes[0] = strings[j].charAt(0); array[j] = new HashedString(hashes, modifiers); } for (int i=1; i<n; i++) { modifiers[i] = (modifiers[i-1] * P) % M; for (int j=0; j<strings.length; j++) { String s = strings[j]; long[] hashes = array[j].hashes; hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M; } } return array; } void initializePandM() { ArrayList<Long> modOptions = new ArrayList<>(20); modOptions.add(353873237L); modOptions.add(353875897L); modOptions.add(353878703L); modOptions.add(353882671L); modOptions.add(353885303L); modOptions.add(353888377L); modOptions.add(353893457L); P = modOptions.get(new Random().nextInt(modOptions.size())); modOptions.clear(); modOptions.add(452940277L); modOptions.add(452947687L); modOptions.add(464478431L); modOptions.add(468098221L); modOptions.add(470374601L); modOptions.add(472879717L); modOptions.add(472881973L); M = modOptions.get(new Random().nextInt(modOptions.size())); } } private static class Prob { /** For heavy calculations on probabilities, this class * provides more accuracy & efficiency than doubles. * Math explained: https://en.wikipedia.org/wiki/Log_probability * Quick start: * - Instantiate probabilities, eg. Prob a = new Prob(0.75) * - add(), multiply() return new objects, can perform on nulls & NaNs. * - get() returns probability as a readable double */ /** Logarithmized probability. Note: 0% represented by logP NaN. */ private double logP; /** Construct instance with real probability. */ public Prob(double real) { if (real > 0) this.logP = Math.log(real); else this.logP = Double.NaN; } /** Construct instance with already logarithmized value. */ static boolean dontLogAgain = true; public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) { this.logP = logP; } /** Returns real probability as a double. */ public double get() { return Math.exp(logP); } @Override public String toString() { return ""+get(); } /***************** STATIC METHODS BELOW ********************/ /** Note: returns NaN only when a && b are both NaN/null. */ public static Prob add(Prob a, Prob b) { if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain); if (nullOrNaN(a)) return copy(b); if (nullOrNaN(b)) return copy(a); double x = Math.max(a.logP, b.logP); double y = Math.min(a.logP, b.logP); double sum = x + Math.log(1 + Math.exp(y - x)); return new Prob(sum, dontLogAgain); } /** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */ public static Prob multiply(Prob a, Prob b) { if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain); return new Prob(a.logP + b.logP, dontLogAgain); } /** Returns true if p is null or NaN. */ private static boolean nullOrNaN(Prob p) { return (p == null || Double.isNaN(p.logP)); } /** Returns a new instance with the same value as original. */ private static Prob copy(Prob original) { return new Prob(original.logP, dontLogAgain); } } public class StronglyConnectedComponents { /** Kosaraju's algorithm */ ArrayList<Integer>[] forw; ArrayList<Integer>[] bacw; /** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */ public int getCount(int n, int[] mista, int[] minne) { forw = new ArrayList[n+1]; bacw = new ArrayList[n+1]; for (int i=1; i<=n; i++) { forw[i] = new ArrayList<Integer>(); bacw[i] = new ArrayList<Integer>(); } for (int i=0; i<mista.length; i++) { int a = mista[i]; int b = minne[i]; forw[a].add(b); bacw[b].add(a); } int count = 0; List<Integer> list = new ArrayList<Integer>(); boolean[] visited = new boolean[n+1]; for (int i=1; i<=n; i++) { dfsForward(i, visited, list); } visited = new boolean[n+1]; for (int i=n-1; i>=0; i--) { int node = list.get(i); if (visited[node]) continue; count++; dfsBackward(node, visited); } return count; } public void dfsForward(int i, boolean[] visited, List<Integer> list) { if (visited[i]) return; visited[i] = true; for (int neighbor : forw[i]) { dfsForward(neighbor, visited, list); } list.add(i); } public void dfsBackward(int i, boolean[] visited) { if (visited[i]) return; visited[i] = true; for (int neighbor : bacw[i]) { dfsBackward(neighbor, visited); } } } class DrawGrid { void draw(boolean[][] d) { System.out.print(" "); for (int x=0; x<d[0].length; x++) { System.out.print(" " + x + " "); } System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print((d[y][x] ? "[x]" : "[ ]")); } System.out.println(""); } } void draw(int[][] d) { int max = 1; for (int y=0; y<d.length; y++) { for (int x=0; x<d[0].length; x++) { max = Math.max(max, ("" + d[y][x]).length()); } } System.out.print(" "); String format = "%" + (max+2) + "s"; for (int x=0; x<d[0].length; x++) { System.out.print(String.format(format, x) + " "); } format = "%" + (max) + "s"; System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print(" [" + String.format(format, (d[y][x])) + "]"); } System.out.println(""); } } } class BaseConverter { /* Palauttaa luvun esityksen kannassa base */ public String convert(Long number, int base) { return Long.toString(number, base); } /* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku StringinΓ€ kannassa baseFrom */ public String convert(String number, int baseFrom, int baseTo) { return Long.toString(Long.parseLong(number, baseFrom), baseTo); } /* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */ public long longify(String number, int baseFrom) { return Long.parseLong(number, baseFrom); } } class Binary implements Comparable<Binary> { /** * Use example: Binary b = new Binary(Long.toBinaryString(53249834L)); * * When manipulating small binary strings, instantiate new Binary(string) * When just reading large binary strings, instantiate new Binary(string,true) * get(int i) returns a character '1' or '0', not an int. */ private boolean[] d; private int first; // Starting from left, the first (most remarkable) '1' public int length; public Binary(String binaryString) { this(binaryString, false); } public Binary(String binaryString, boolean initWithMinArraySize) { length = binaryString.length(); int size = Math.max(2*length, 1); first = length/4; if (initWithMinArraySize) { first = 0; size = Math.max(length, 1); } d = new boolean[size]; for (int i=0; i<length; i++) { if (binaryString.charAt(i) == '1') d[i+first] = true; } } public void addFirst(char c) { if (first-1 < 0) doubleArraySize(); first--; d[first] = (c == '1' ? true : false); length++; } public void addLast(char c) { if (first+length >= d.length) doubleArraySize(); d[first+length] = (c == '1' ? true : false); length++; } private void doubleArraySize() { boolean[] bigArray = new boolean[(d.length+1) * 2]; int newFirst = bigArray.length / 4; for (int i=0; i<length; i++) { bigArray[i + newFirst] = d[i + first]; } first = newFirst; d = bigArray; } public boolean flip(int i) { boolean value = (this.d[first+i] ? false : true); this.d[first+i] = value; return value; } public void set(int i, char c) { boolean value = (c == '1' ? true : false); this.d[first+i] = value; } public char get(int i) { return (this.d[first+i] ? '1' : '0'); } @Override public int compareTo(Binary o) { if (this.length != o.length) return this.length - o.length; int len = this.length; for (int i=0; i<len; i++) { int diff = this.get(i) - o.get(i); if (diff != 0) return diff; } return 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i=0; i<length; i++) { sb.append(d[i+first] ? '1' : '0'); } return sb.toString(); } } class BinomialCoefficients { /** Total number of K sized unique combinations from pool of size N (unordered) N! / ( K! (N - K)! ) */ /** For simple queries where output fits in long. */ public long biCo(long n, long k) { long r = 1; if (k > n) return 0; for (long d = 1; d <= k; d++) { r *= n--; r /= d; } return r; } /** For multiple queries with same n, different k. */ public long[] precalcBinomialCoefficientsK(int n, int maxK) { long v[] = new long[maxK+1]; v[0] = 1; // nC0 == 1 for (int i=1; i<=n; i++) { for (int j=Math.min(i,maxK); j>0; j--) { v[j] = v[j] + v[j-1]; // Pascal's triangle } } return v; } /** When output needs % MOD. */ public long[] precalcBinomialCoefficientsK(int n, int k, long M) { long v[] = new long[k+1]; v[0] = 1; // nC0 == 1 for (int i=1; i<=n; i++) { for (int j=Math.min(i,k); j>0; j--) { v[j] = v[j] + v[j-1]; // Pascal's triangle v[j] %= M; } } return v; } } class Trie { int N; int Z; int nextFreeId; int[][] pointers; boolean[] end; /** maxLenSum = maximum possible sum of length of words */ public Trie(int maxLenSum, int alphabetSize) { this.N = maxLenSum; this.Z = alphabetSize; this.nextFreeId = 1; pointers = new int[N+1][alphabetSize]; end = new boolean[N+1]; } public void addWord(String word) { int curr = 0; for (int j=0; j<word.length(); j++) { int c = word.charAt(j) - 'a'; int next = pointers[curr][c]; if (next == 0) { next = nextFreeId++; pointers[curr][c] = next; } curr = next; } int last = word.charAt(word.length()-1) - 'a'; end[last] = true; } public boolean hasWord(String word) { int curr = 0; for (int j=0; j<word.length(); j++) { int c = word.charAt(j) - 'a'; int next = pointers[curr][c]; if (next == 0) return false; curr = next; } int last = word.charAt(word.length()-1) - 'a'; return end[last]; } } private class IO extends PrintWriter { private InputStreamReader r; private static final int BUFSIZE = 1 << 15; private char[] buf; private int bufc; private int bufi; private StringBuilder sb; public IO() { super(new BufferedOutputStream(System.out)); r = new InputStreamReader(System.in); buf = new char[BUFSIZE]; bufc = 0; bufi = 0; sb = new StringBuilder(); } /** Print, flush, return nextInt. */ private int queryInt(String s) { io.println(s); io.flush(); return nextInt(); } /** Print, flush, return nextLong. */ private long queryLong(String s) { io.println(s); io.flush(); return nextLong(); } /** Print, flush, return next word. */ private String queryNext(String s) { io.println(s); io.flush(); return next(); } private void fillBuf() throws IOException { bufi = 0; bufc = 0; while(bufc == 0) { bufc = r.read(buf, 0, BUFSIZE); if(bufc == -1) { bufc = 0; return; } } } private boolean pumpBuf() throws IOException { if(bufi == bufc) { fillBuf(); } return bufc != 0; } private boolean isDelimiter(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; } private void eatDelimiters() throws IOException { while(true) { if(bufi == bufc) { fillBuf(); if(bufc == 0) throw new RuntimeException("IO: Out of input."); } if(!isDelimiter(buf[bufi])) break; ++bufi; } } public String next() { try { sb.setLength(0); eatDelimiters(); int start = bufi; while(true) { if(bufi == bufc) { sb.append(buf, start, bufi - start); fillBuf(); start = 0; if(bufc == 0) break; } if(isDelimiter(buf[bufi])) break; ++bufi; } sb.append(buf, start, bufi - start); return sb.toString(); } catch(IOException e) { throw new RuntimeException("IO.next: Caught IOException."); } } public int nextInt() { try { int ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextInt: Invalid int."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int."); ret *= 10; ret -= (int)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int."); } else { throw new RuntimeException("IO.nextInt: Invalid int."); } ++bufi; } if(positive) { if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextInt: Caught IOException."); } } public long nextLong() { try { long ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextLong: Invalid long."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long."); ret *= 10; ret -= (long)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long."); } else { throw new RuntimeException("IO.nextLong: Invalid long."); } ++bufi; } if(positive) { if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextLong: Caught IOException."); } } 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
n = int(raw_input()) a = map(int, raw_input().split()) diffs = [max(a[i]-a[i+1], a[i+1]-a[i]) for i in range(len(a)-1)] max_best = 0 max_to_here1 = 0 max_to_here2 = 0 #print(diffs) for i in range(len(diffs)): max_to_here1 =max(0, max_to_here1+ diffs[i] *(-1)**i) max_to_here2 =max(0, max_to_here2 +diffs[i] * (-1) ** (i+1)) max_best = max(max_best, max_to_here1, max_to_here2) print(max_best)
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
from itertools import accumulate inf = 10**9 + 1 def solve(): n = int(input()) a = [int(i) for i in input().split()] ad = [abs(a[i + 1] - a[i]) for i in range(n - 1)] ap = [0] + list(accumulate(ai*(-1)**i for i, ai in enumerate(ad))) max_dif, max_mdif = max_min_profit(ap) ans = max(max_dif, max_mdif) print(ans) def max_min_profit(a): max_dif = 0 max_mdif = 0 min_v = max_v = 0 for i in range(1, len(a)): if a[i] < min_v: min_v = a[i] else: max_dif = max(max_dif, a[i] - min_v) if a[i] > max_v: max_v = a[i] else: max_mdif = max(max_mdif, max_v - a[i]) return max_dif, max_mdif if __name__ == '__main__': solve()
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> inline int two(int n) { return 1 << n; } inline int test(int n, int b) { return (n >> b) & 1; } inline void set_bit(int& n, int b) { n |= two(b); } inline void unset_bit(int& n, int b) { n &= ~two(b); } inline int last_bit(int n) { return n & (-n); } inline int ones(int n) { int res = 0; while (n && ++res) n -= n & (-n); return res; } long long int gcd(long long int a, long long int b) { return (a ? gcd(b % a, a) : b); } long long int modPow(long long int a, long long int b, long long int MOD) { long long int x = 1, y = a; while (b > 0) { if (b % 2 == 1) { x = (x * y) % MOD; } b /= 2; y = (y * y) % MOD; } return x; } long long int modInverse(long long int a, long long int p) { return modPow(a, p - 2, p); } using namespace std; const int N = 1e5 + 5; long long int a[N]; long long int b[N]; long long int c[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); long long int n, i, j, ans1, ans2; cin >> n; for (i = 0; i < n; i++) cin >> a[i]; for (i = 0; i < n - 1; i++) { b[i] = abs(a[i] - a[i + 1]); if (i % 2 == 0) c[i] = -b[i]; else { c[i] = b[i]; b[i] *= -1; } } long long int s = 0LL; ans1 = ans2 = 0LL; for (int i = 0; i < (n - 1); i++) { s += b[i]; if (s > ans1) ans1 = s; else if (s < 0) s = 0; } s = 0; for (int i = 0; i < (n - 1); i++) { s += c[i]; if (s > ans2) ans2 = s; else if (s < 0) s = 0; } cout << max(ans1, ans2); 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 int kadane(vector<long long int> v) { if (v.size() == 0) return INT_MIN; long long int n = v.size(); long long int curr_max = v[0], ans = v[0]; for (int i = 1; i < n; i++) { curr_max = max(curr_max + v[i], v[i]); ans = max(curr_max, ans); } return ans; } int main() { long long int n; scanf("%lld", &n); long long int a[n]; for (__typeof(n) i = 0 - (0 > n); i != n - (0 > n); i += 1 - 2 * (0 > n)) scanf("%lld", &a[i]); vector<long long int> v; for (int i = 1; i < n; i++) { v.push_back(abs(a[i] - a[i - 1])); if (i % 2 == 0) v[i - 1] *= -1; } long long int ans1 = kadane(v); reverse(v.begin(), v.end()); v.pop_back(); reverse(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) v[i] *= -1; long long int ans2 = kadane(v); printf("%lld\n", max(ans1, ans2)); 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())) d = [abs(a[i] - a[i+1]) * (-1)**i for i in range(n-1)] maxsum1 = 0 sum1 = 0 for di in d: if di > 0 or abs(di) < abs(sum1): sum1 += di else: sum1 = 0 maxsum1 = max(maxsum1, abs(sum1)) sum1 = 0 for di in d[1:]: if di < 0 or abs(di) < abs(sum1): sum1 += di else: sum1 = 0 maxsum1 = max(maxsum1, abs(sum1)) print(maxsum1)
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.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import static java.lang.Math.max; import static java.lang.Math.abs; public class Code_788A_FunctionsAgain { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); StringTokenizer in=new StringTokenizer(br.readLine()); int n=Integer.parseInt(in.nextToken()); in=new StringTokenizer(br.readLine()); long[] a=new long[n]; long[] odd=new long[n-1]; long[] even=new long[n-1]; a[0]=Long.parseLong(in.nextToken()); for(int i=1;i<n;++i) { a[i] = Long.parseLong(in.nextToken()); odd[i-1]=abs(a[i]-a[i-1])*(i%2==1?1:-1); even[i-1]=-odd[i-1]; } out.println(max(solve(odd),solve(even))); out.close(); } public static long solve(long[] a){ long max=a[0],currentMax=a[0],n=a.length; for(int i=1;i<n;++i){ currentMax=max(currentMax+a[i],a[i]); max=max(max,currentMax); } return 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() { int n, i; long long sum = 0, z = 0, s = 0, m = 0, mm = 0; cin >> n; vector<long long> a(n); for (i = 0; i < n; i++) cin >> a[i]; for (i = 0; i < (n - 1); i++) { if (i % 2 == 0) sum = sum + abs(a[i + 1] - a[i]); else sum = max(z, sum - abs(a[i + 1] - a[i])); m = max(m, sum); } for (i = 1; i < (n - 1); i++) { if (i % 2 == 1) s = s + abs(a[i + 1] - a[i]); else s = max(z, s - abs(a[i + 1] - a[i])); m = max(s, m); } cout << m; }
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.Arrays; import java.util.StringTokenizer; public class c { public static void main(String[] args) throws NumberFormatException, IOException { FastScanner in = new FastScanner(System.in); int n = in.nextInt(); long[] diff = new long[n-1]; long cur = in.nextInt(); long prev = in.nextInt(); diff[0] = Math.abs(cur-prev); for (int i = 1; i < diff.length; i++) { cur = in.nextInt(); diff[i] = Math.abs(cur-prev); prev = cur; } //System.out.println(Arrays.toString(diff)); long[] even = new long[n], odd = new long[n]; for (int i = 1; i < even.length; i++) { even[i] = even[i-1]; odd[i] = odd[i-1]; if(i%2==0){ even[i] += diff[i-1]; } else { odd[i] += diff[i-1]; } } long[] arr =new long[n]; for (int i = 0; i < odd.length; i++) { arr[i] = even[i] - odd[i]; } long max = 0; long min = 0; for (int i = 0; i < arr.length; i++) { if(arr[i] > max)max = arr[i]; if(arr[i] < min)min = arr[i]; } // System.out.println(max + " " + min); // System.out.println(Arrays.toString(arr)); System.out.println(Math.abs(max - min)); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public 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
n=int(raw_input()) N=map(int,raw_input().split()) b=[] c=[] ans=0 for i in range(1,n): b.append(abs(N[i]-N[i-1])) c.append(abs(N[i-1]-N[i])) for i in range(len(b)): if i%2!=0: b[i]= -b[i] else: c[i]= -c[i] maxso= -(10**20)-1 maxe=0 for i in range(len(b)): maxe=maxe+b[i] if maxso<maxe: maxso=maxe if maxe<0: maxe=0 ans=max(ans,maxso) maxso= -(10**20)-1 maxe=0 for i in range(len(b)): maxe=maxe+c[i] if maxso<maxe: maxso=maxe if maxe<0: maxe=0 print max(ans,maxso)
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> using namespace std; #pragma comment(linker, "/STACK:102400000,102400000") const long long INF = 1e18 + 1LL; const double Pi = acos(-1.0); const int N = 1e5 + 10, M = 1e3 + 20, mod = 1e9 + 7, inf = 2e9; int n, a[N], b[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i < n; ++i) { int tmp = (i % 2 == 0) ? -1 : 1; b[i] = abs(a[i] - a[i + 1]) * tmp; } long long ans1 = 0, maxsum1 = b[1]; for (int i = 1; i < n; i++) { ans1 += b[i]; if (ans1 > maxsum1) { maxsum1 = ans1; } if (ans1 < 0) { ans1 = 0; } } long long ans2 = 0; long long maxsum2 = -b[1]; for (int i = 1; i < n; i++) { ans2 += -b[i]; if (ans2 > maxsum2) { maxsum2 = ans2; } if (ans2 < 0) { ans2 = 0; } } cout << max(maxsum1, maxsum2) << 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.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int[]a = new int[n+1]; for (int i = 1; i <= n; i++) { a[i] = nextInt(); } long[]b = new long[n+1]; long sum_odd = 0, sum_even = 0; for (int i = 1; i < n; i++) { b[i] = Math.abs(a[i]-a[i+1]); } long ans = Long.MIN_VALUE; long min1 = 0, min2 = 0; for (int i = n-1; i >= 1; i--) { if (i % 2==0) { sum_even += b[i]; } else { sum_odd += b[i]; } if (i % 2==0) { ans = Math.max(ans, sum_even-sum_odd - min1); } else { ans = Math.max(ans, sum_odd-sum_even - min2); } min1 = Math.min(min1, sum_even-sum_odd); min2 = Math.min(min2, sum_odd-sum_even); } System.out.println(ans); pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.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
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector<long long int> b(n), c(n); b[n - 1] = 0, c[n - 1] = 0; b[n - 2] = abs(a[n - 2] - a[n - 1]); c[n - 2] = b[n - 2]; if (n > 2) { b[n - 3] = abs(a[n - 3] - a[n - 2]); c[n - 3] = b[n - 3] - b[n - 2]; for (int i = n - 4; i > -1; i--) { b[i] = abs(a[i] - a[i + 1]) - min(c[i + 1], 0LL); c[i] = abs(a[i] - a[i + 1]) - max(b[i + 1], 0LL); } } cout << *max_element(b.begin(), b.end()); 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; import java.io.PrintWriter; import java.util.StringTokenizer; public class CF788A { public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); pw.println(solve(a)); sc.close(); pw.close(); } public static long solve(int[] a) { int n = a.length; long currSum1 = 0; // alternate signs, start with +ve long currSum2 = 0; // alternate signs, start with -ve long maxSum = 0; for (int i = 0; i < n - 1; i++) { long diff = Math.abs(0l + a[i] - a[i + 1]); currSum1 = Math.max(0, (i & 1) == 0 ? currSum1 + diff : currSum1 - diff); currSum2 = Math.max(0, (i & 1) == 0 ? currSum2 - diff : currSum2 + diff); maxSum = Math.max(maxSum, Math.max(currSum1, currSum2)); } return maxSum; } static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner() { this.in = new BufferedReader(new InputStreamReader(System.in)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } public void close() throws IOException { 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
#include <bits/stdc++.h> using namespace std; long long a[105000]; long long b[105000]; long long n; long long gao() { long long x = 0, ret = 0; for (long long i = 1; i < n; i++) { x += b[i]; ret = max(ret, x); if (x < 0) x = 0; } return ret; } signed main() { cin >> n; for (long long i = 1; i <= n; i++) cin >> a[i]; for (long long i = 1; i < n; i++) { b[i] = a[i] - a[i + 1]; if (b[i] < 0) b[i] *= -1; if (i % 2 == 0) b[i] *= -1; } long long r = gao(); for (long long i = 1; i < n; i++) b[i] *= -1; r = max(r, gao()); cout << r << 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; template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } const int oo = 0x3f3f3f3f; const int maxn = 100100; int n; int a[maxn + 5], b[maxn + 5]; long long sum[maxn + 5]; int main() { scanf("%d", &n); for (int i = (0), i_end_ = (n); i < i_end_; ++i) scanf("%d", a + i); for (int i = (0), i_end_ = (n - 1); i < i_end_; ++i) b[i] = abs(a[i] - a[i + 1]); long long Max0 = 0, Max1 = 0; sum[n - 1] = 0; long long ans = 0; for (int i = n - 2; i >= 0; --i) { sum[i] = sum[i + 1] + ((i & 1) ? -b[i] : b[i]); chkmax(Max0, -sum[i]); chkmax(Max1, sum[i]); if (i & 1) chkmax(ans, -sum[i] + Max1); else chkmax(ans, sum[i] + Max0); } cout << ans << endl; return 0; }
CPP