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
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 4; long long int a[maxn], dif1[maxn], dif2[maxn]; long long int kadane(long long int arr[], int n) { long long int ans = -2e9, curr_max = -2e9; for (int i = 1; i < n; i++) { curr_max = max(arr[i], curr_max + arr[i]); ans = max(curr_max, ans); } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } long long int tog = -1LL; for (int i = 1; i < n; i++) { dif1[i] = tog * abs(a[i + 1] - a[i]); dif2[i] = -1LL * dif1[i]; tog = -1 * tog; } long long int ans = max(kadane(dif1, n), kadane(dif2, n)); cout << ans; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; void solve(); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(0); solve(); return 0; } long long maxA = LONG_MIN, max_ending_here = 0, maxB = LONG_MIN, sumA = 0, sumB = 0; bool A = 0, B = 0; void solve() { int n; cin >> n; vector<long long> v(n), a(n), b(n); for (int i = 0; i < n; i++) cin >> v[i]; for (int i = 0; i < n - 1; i++) { a[i] = abs(v[i] - v[i + 1]); b[i] = a[i]; } a[n - 1] = b[n - 1] = v[n - 1]; for (int i = 0; i < n; i++) { if (i % 2 == 0) { a[i] *= (-1); } else { b[i] *= (-1); } } for (int i = 0; i < n - 1; i++) { max_ending_here = max_ending_here + a[i]; if (maxA < max_ending_here) { maxA = max_ending_here; } if (max_ending_here < 0) { max_ending_here = 0; } } max_ending_here = 0; for (int i = 0; i < n - 1; i++) { max_ending_here = max_ending_here + b[i]; if (maxB < max_ending_here) { maxB = max_ending_here; } if (max_ending_here < 0) { max_ending_here = 0; } } cout << (1ll) * max(maxA, maxB); }
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 n, res, a[1 << 17], S[1 << 17], mx, mi; int main() { cin >> n; for (int i = 1; i <= n; i++) scanf("%lld", a + i); for (int i = 1; i < n; i++) { S[i] = S[i - 1] + abs(a[i] - a[i + 1]) * (i & 1 ? 1 : -1); res = max(res, max(mx - S[i], S[i] - mi)), i& 1 ? mx = max(mx, S[i]) : mi = min(mi, S[i]); } cout << res << 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; int main() { ios_base ::sync_with_stdio(0); long long int n, k; cin >> n; long long int a[n + 1]; for (int i = 0; i < n; i++) { cin >> a[i]; } long long int mx1 = -1e9, mx2 = -1e9, c1 = 0, c2 = 0; for (int i = 0; i < n - 1; i++) { long long int aux = fabs(a[i + 1] - a[i]) * powf(-1, i % 2 != 0); c1 += aux; mx1 = max(c1, mx1); if (c1 < 0) c1 = 0; } for (int i = 1; i < n - 1; i++) { long long int aux = fabs(a[i + 1] - a[i]) * powf(-1, i % 2 == 0); c2 += aux; mx2 = max(c2, mx2); if (c2 < 0) c2 = 0; } cout << max(mx1, mx2) << endl; ; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.util.*; public class ProblemC { static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[50000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static long maxSubarray(long[] a){ long max_so_far = Long.MIN_VALUE; long max_ending_here = 0; for(int i=0;i<a.length;i++){ max_ending_here+=a[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; } public static void print(long[]a){ for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(""); } public static void main(String[] args)throws IOException{ Reader in =new Reader(); OutputWriter out=new OutputWriter(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=0;i<n-1;i++){ if(i%2==0){ b[i]=Math.abs(a[i]-a[i+1]); c[i]=-b[i]; } else{ c[i]=Math.abs(a[i+1]-a[i]); b[i]=-c[i]; } } // print(b); // print(c); out.printLine(Math.max(maxSubarray(b), maxSubarray(c))); out.flush(); } }
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 i; long long a[100005]; long long b[100005]; int main() { int n; cin >> n; for (i = 1; i <= n; i++) { cin >> a[i]; } for (i = 1; i < n; i++) { b[i] = llabs(a[i] - a[i + 1]); } long long bestSum = -200000000000000000LL, sum = 0, sum2 = 0, maxim = -200000000000000000LL, idx = 1; long long minim = 0, minales; for (i = 1; i < n; i++) { if ((i - idx) % 2 == 1) { sum = sum - b[i]; } else sum = sum + b[i]; if (sum > maxim) { maxim = sum; minales = minim; } if (sum < minim) { minim = sum; } } idx = 1, sum = 0; bestSum = maxim - minales; maxim = -200000000000000000LL; minim = minales = 0; for (i = 2; i < n; i++) { if ((i - idx) % 2 == 0) { sum = sum - b[i]; } else sum = sum + b[i]; if (sum > maxim) { maxim = sum; minales = minim; } if (sum < minim) { minim = sum; } } if (bestSum < maxim - minales) { bestSum = maxim - minales; } cout << bestSum; }
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())) aux = 0 minaux = 0 maxim = 0 results = [] for i in range(1, n): results.append(abs(a[i-1] - a[i])) for i in range(0,n-1): if i%2 == 1: condition = -results[i] else: condition = results[i] aux += condition minaux -= condition if aux > maxim: maxim = aux if condition > maxim: maxim = condition if minaux > maxim: maxim = minaux if minaux < 0: minaux = 0 if aux < 0: aux = 0 print (maxim)
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 = 2e5 + 5; const int MOD = 1e9 + 7; long long dp[N][2][2]; int arr[N]; int n; long long solve(int idx, bool take, int sign) { if (idx == n) return 0; long long& cur = dp[idx][take][sign + 1]; if (cur != -1) return cur; if (take) { return cur = max(0ll, ((long long)(arr[idx] * sign)) + solve(idx + 1, take, sign * -1)); } else { return cur = max(solve(idx + 1, take, sign), arr[idx] + solve(idx + 1, 1, -1)); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); memset(dp, -1, sizeof(dp)); int num; cin >> n >> num; --n; for (int i = 0; i < n; ++i) { int cur; cin >> cur; arr[i] = abs(cur - num); num = cur; } cout << solve(0, 0, 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; long long v[100005], dp[100005], Max; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for (int i = 1; i <= n; i++) cin >> v[i]; for (int i = 1; i <= n - 1; i++) v[i] = abs(v[i] - v[i + 1]); n--; for (int i = 1; i <= n; i++) { dp[i] = v[i]; if (i + 2 >= 3) dp[i] = max(dp[i], v[i] - v[i - 1] + dp[i - 2]); Max = max(Max, dp[i]); } cout << Max; }
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 App { public static void main(String[] args) { Scanner inp = new Scanner(System.in); int n = inp.nextInt(); int[] arr = new int[n + 1]; for (int i = 1; i <= n; i++) { arr[i] = inp.nextInt(); } for (int i = 1; i < n; i++) { arr[i] -= arr[i + 1]; arr[i] = Math.abs(arr[i]); } long sum = 0, tsum = 0; int prev = 1; for (int i = 1; i < n; i++) { if ((i - prev) % 2 == 0) { tsum += arr[i]; } else { tsum -= arr[i]; } if (tsum < 0) { tsum = 0; prev = i + 1; } if (tsum > sum) { sum = tsum; } } long res = sum; prev = 2; tsum = 0; sum = 0; for (int i = 2; i < n; i++) { if ((i - prev) % 2 == 0) { tsum += arr[i]; } else { tsum -= arr[i]; } if (tsum < 0) { tsum = 0; prev = i + 1; } if (tsum > sum) { sum = tsum; } } if(res < sum) { res = sum; } System.out.println(res); inp.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 long long mod = 1e9 + 7; const long long INF = 0x7FFFFFFFFFFFFFFF / 2; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n; cin >> n; long long arr[n]; vector<long long> pos, neg; for (int i = 0; i < n; i++) { cin >> arr[i]; } long long sig = 1; for (int i = 0; i < n - 1; i++) { pos.push_back(sig * abs(arr[i + 1] - arr[i])); sig *= -1; } sig = 1; for (int i = 1; i < n - 1; i++) { neg.push_back(sig * abs(arr[i + 1] - arr[i])); sig *= -1; } long long ans_maximus = -INT_MAX; long long max_so_far = -INT_MAX, max_ending_here = 0; for (int i = 0; i < pos.size(); i++) { max_ending_here = max_ending_here + pos[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } ans_maximus = max(ans_maximus, max_so_far); max_so_far = -INT_MAX, max_ending_here = 0; for (int i = 0; i < neg.size(); i++) { max_ending_here = max_ending_here + neg[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } ans_maximus = max(ans_maximus, max_so_far); cout << ans_maximus; 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; using ld = long double; int t[102], low[102], high[102]; using ull = unsigned long long; int mod = pow(10, 9) + 7; long long int arr[200009], val[200009], ans[200009]; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> arr[i]; for (int i = 1; i < n; i++) val[i] = abs(arr[i] - arr[i + 1]); ans[1] = val[1]; long long int res = ans[1]; for (int i = 2; i < n; i++) { long long int tmp = val[i] - val[i - 1] + ans[i - 2]; ans[i] = max(val[i], tmp); res = max(res, ans[i]); } cout << res; 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 Daniel { public static void main (String[] args) { Scanner dank = new Scanner(System.in); int n = dank.nextInt(); int [] a = new int [n]; int [] b = new int [n-1]; for(int d = 0; d<n; d++) { a[d] = dank.nextInt(); } for(int d = 0; d<n-1; d++) { b[d] = Math.abs(a[d] - a[d+1]); } long x = b[0]; long max = x; long y = 0; for(int d = 1; d<n-1; d++) { if(d%2 == 1) { x = x - b[d]; if(x<0) { x=0; } if(x> max) { max = x; } } else { x = x + b[d]; if(x<0) { x=0; } if(x> max) { max = x; } } if(d%2 == 1) { y = y + b[d]; if(y<0) { y=0; } if(y> max) { max = y; } } else { y = y - b[d]; if(y<0) { y=0; } if(y> max) { max = y; } } } System.out.print(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 A { public static void solution(BufferedReader reader, PrintWriter writer) throws IOException { In in = new In(reader); Out out = new Out(writer); int n = in.nextInt(); int[] a = in.nextIntArray(n); long[] even = new long[n]; long[] odd = new long[n]; for (int i = 0; i < n - 1; i++) { even[i] = Math.abs(a[i] - a[i + 1]) * (i % 2 == 0 ? 1 : -1); odd[i] = Math.abs(a[i] - a[i + 1]) * (i % 2 == 0 ? -1 : 1); } odd[0] = 0; long evensum = 0, evenmin = 0, evenmax = 0; long oddsum = 0, oddmin = 0, oddmax = 0; for (int i = 0; i < n - 1; i++) { evensum += even[i]; evenmin = Math.min(evenmin, evensum); evenmax = Math.max(evensum - evenmin, evenmax); oddsum += odd[i]; oddmin = Math.min(oddmin, oddsum); oddmax = Math.max(oddsum - oddmin, oddmax); } out.println(Math.max(evenmax, oddmax)); } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, writer); writer.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } protected static class Out { private PrintWriter writer; private static boolean local = System .getProperty("ONLINE_JUDGE") == null; public Out(PrintWriter writer) { this.writer = writer; } public void print(char c) { writer.print(c); } public void print(int a) { writer.print(a); } public void printb(int a) { writer.print(a); writer.print(' '); } public void println(Object a) { writer.println(a); } public void println(Object[] os) { for (int i = 0; i < os.length; i++) { writer.print(os[i]); writer.print(' '); } writer.println(); } public void println(int[] a) { for (int i = 0; i < a.length; i++) { writer.print(a[i]); writer.print(' '); } writer.println(); } public void println(long[] a) { for (int i = 0; i < a.length; i++) { writer.print(a[i]); writer.print(' '); } writer.println(); } public void flush() { writer.flush(); } public static void db(Object... objects) { if (local) System.out.println(Arrays.deepToString(objects)); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int a[100 * 1000]; int b[100 * 1000]; int main() { ios::sync_with_stdio(false); int n; long long max = (-1) * 1e15, maxn, maxp; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; maxn = maxp = abs(a[n - 2] - a[n - 1]); for (int i = n - 2; i >= 0; i--) { long long t = maxn; maxn = abs(a[i] - a[i + 1]) - maxp; maxp = abs(a[i] - a[i + 1]) - t; if (maxp < abs(a[i] - a[i + 1])) maxp = abs(a[i] - a[i + 1]); if (maxp > max) max = maxp; } cout << max << endl; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; const int INF = 0x3f3f3f3f; const double eps = 1e-8; inline int read() { int ans = 0, flag = 1; char c; c = getchar(); while (c < '0' || c > '9') { if (c == '-') flag = -1; c = getchar(); } while (c >= '0' && c <= '9') { ans = ans * 10 + (int)(c - '0'); c = getchar(); } return ans * flag; } long long quickpow(long long x, long long y, long long mod) { long long ans = x % mod; while (y) { if (y & 1) ans = ans * x % mod; x = x * x % mod; y >>= 1; } return ans; } long long num[maxn]; long long num1[maxn], num2[maxn]; long long dp[maxn]; int main() { int n; while (cin >> n) { long long last; long long ans = 0; for (int i = 0; i < n; i++) num[i] = read(); for (int i = 0; i < n - 1; i++) num1[i + 1] = abs(num[i + 1] - num[i]) * (i % 2 == 0 ? 1 : -1); for (int i = 1; i < n - 1; i++) num2[i] = abs(num[i + 1] - num[i]) * (i % 2 == 0 ? -1 : 1); memset(dp, 0, sizeof dp); for (int i = 1; i <= n - 1; i++) { dp[i] = max(0LL, dp[i - 1]) + num1[i]; ans = max(ans, dp[i]); } memset(dp, 0, sizeof dp); for (int i = 1; i <= n - 2; i++) { dp[i] = max(0LL, dp[i - 1]) + num2[i]; ans = max(ans, dp[i]); } cout << ans << endl; } return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int OO = (int)2e9 + 5; const int MOD = (int)1e9 + 7; const long double Pi = 3.141592653589793238; const int N = (int)2e5 + 5; long long qqaGJJ[N], ss[2][N], vRI[2][N], n, uVyh = 0; int main() { cin >> n; for (int i = (int)(1); i <= (int)(n); i++) cin >> qqaGJJ[i]; reverse(qqaGJJ + 1, qqaGJJ + n + 1); for (int i = (int)(1); i <= (int)(n); i++) { if (i == 1) { ss[0][i] = ss[1][0] = 0; vRI[0][i] = vRI[1][i] = 0; } else { for (int k = (int)(0); k <= (int)(1); k++) { ss[k][i] = ss[k][i - 1] + abs(qqaGJJ[i] - qqaGJJ[i - 1]) * (((i + k) % 2) ? 1 : -1); vRI[k][i] = min(vRI[k][i - 1], ss[k][i]); } } } uVyh = ss[1][2]; for (int i = (int)(2); i <= (int)(n); i++) { uVyh = max(uVyh, ss[(i + 1) % 2][i] - vRI[(i + 1) % 2][i - 1]); } cout << uVyh; }
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 sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest # sys.setrecursionlimit(111111) INF=999999999999999999999999 alphabets="abcdefghijklmnopqrstuvwxyz" class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class SegTree: def __init__(self, n): self.N = 1 << n.bit_length() self.tree = [0] * (self.N<<1) def update(self, i, j, v): i += self.N j += self.N while i <= j: if i%2==1: self.tree[i] += v if j%2==0: self.tree[j] += v i, j = (i+1) >> 1, (j-1) >> 1 def query(self, i): v = 0 i += self.N while i > 0: v += self.tree[i] i >>= 1 return v def SieveOfEratosthenes(limit): """Returns all primes not greater than limit.""" isPrime = [True]*(limit+1) isPrime[0] = isPrime[1] = False primes = [] for i in range(2, limit+1): if not isPrime[i]:continue primes += [i] for j in range(i*i, limit+1, i): isPrime[j] = False return primes def main(): mod=1000000007 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") ###CODE tc = 1 for _ in range(tc): n=ri() a=ria() pa=[] na=[] f=0 for i in range(n-1): val=abs(a[i]-a[i+1]) if f: val=-val pa.append(val) na.append(-val) f=1-f maxint=INF def maxSubArraySum(a,size): max_so_far = -maxint - 1 max_ending_here = 0 for i in range(size): max_ending_here = max_ending_here + a[i] max_so_far = max(max_so_far,max_ending_here) max_ending_here = max(0,max_ending_here) return max_so_far wi(max(maxSubArraySum(pa,n-1),maxSubArraySum(na,n-1))) #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) 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, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) 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() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() 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; const int MAX_N = 100000; const int MAX_E2 = 1 << 18; const long long LINF = 1LL << 62; template <typename T, const int MAX_E2> struct SegTreeMinMax { int e2; T mins[MAX_E2], maxs[MAX_E2], inf; SegTreeMinMax() {} void init(int n, T inf) { for (e2 = 1; e2 < n; e2 <<= 1) ; fill(mins, mins + MAX_E2, inf); fill(maxs, maxs + MAX_E2, -inf); } T geti(int i) { return mins[e2 - 1 + i]; } void seti(int i, T v) { mins[e2 - 1 + i] = maxs[e2 - 1 + i] = v; } void set_all() { for (int j = e2 - 2; j >= 0; j--) { int j0 = j * 2 + 1, j1 = j0 + 1; mins[j] = min<T>(mins[j0], mins[j1]); maxs[j] = max<T>(maxs[j0], maxs[j1]); } } pair<T, T> get_range(int r0, int r1, int k, int i0, int i1) { if (r1 <= i0 || i1 <= r0) return pair<T, T>(inf, -inf); if (r0 <= i0 && i1 <= r1) return pair<T, T>(mins[k], maxs[k]); int im = (i0 + i1) / 2; pair<T, T> v0 = get_range(r0, r1, k * 2 + 1, i0, im); pair<T, T> v1 = get_range(r0, r1, k * 2 + 2, im, i1); return pair<T, T>(min<T>(v0.first, v1.first), max<T>(v0.second, v1.second)); } pair<T, T> get_range(int r0, int r1) { return get_range(r0, r1, 0, 0, e2); } T min_range(int r0, int r1) { return get_range(r0, r1).first; } T max_range(int r0, int r1) { return get_range(r0, r1).second; } }; int as[MAX_N]; SegTreeMinMax<long long, MAX_E2> st; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", as + i); st.init(n, LINF); st.seti(0, 0); long long sum = 0; for (int i = 1, sg = 1; i < n; i++, sg *= -1) { sum += abs(as[i - 1] - as[i]) * sg; st.seti(i, sum); } st.set_all(); long long mind = 0, maxd = 0; for (int i = 0; i < n; i++) { pair<long long, long long> v = st.get_range(i, n); long long d0 = v.first - st.geti(i), d1 = v.second - st.geti(i); if (!(i & 1)) { if (maxd < d1) maxd = d1; } else { if (mind > d0) mind = d0; } } printf("%lld\n", max(-mind, maxd)); 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 Round_407; import java.util.Scanner; public class C { private void println(Object obj) { System.out.println(obj); } public C() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long[] a = new long[n]; long[] b = new long[n - 1]; long[] c = new long[n - 1]; a[0] = sc.nextLong(); for (int i = 1; i < n; i++) { a[i] = sc.nextLong(); b[i - 1] = Math.abs(a[i - 1] - a[i]) * (i % 2 != 0 ? -1 : 1); c[i - 1] = Math.abs(a[i - 1] - a[i]) * (i % 2 == 0 ? -1 : 1); } long max = b[0]; long maxe = b[0]; for (int i = 1; i < b.length; i++) { maxe = Math.max(b[i], maxe + b[i]); max = Math.max(max, maxe); } long maxc = c[0]; long maxec = c[0]; for (int i = 1; i < c.length; i++) { maxec = Math.max(c[i], maxec + c[i]); maxc = Math.max(maxc, maxec); } println(Math.max(max, maxc)); sc.close(); } public static void main(String[] args) { new C(); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long n, arr[100005], dif[100005]; long long tot, tot2; int main() { long long ans = 0; ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n; for (int i = 1; i <= n; i++) { cin >> arr[i]; } for (int i = 1; i < n; i++) { dif[i] = abs(arr[i] - arr[i + 1]); } for (int i = 1; i < n; i++) { if (i & 1) { tot += dif[i]; } else { tot -= dif[i]; } tot = max(tot, 0LL); ans = max(ans, tot); } for (int i = 1; i < n; i++) { if (i & 1) { tot2 -= dif[i]; } else { tot2 += dif[i]; } tot2 = max(tot2, 0LL); ans = max(ans, tot2); } cout << ans << endl; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; import java.lang.Math; public class Functions { public long fun(int n, long[] array) { long[] newarray = new long[n - 1]; for (int i = 0; i < n - 1; i++) { newarray[i] = Math.abs(array[i] - array[i + 1]); } long sum = 0; long sum2 = 0; long maxSum = 0; for (int i = 0; i < n - 1; i++) { long current = newarray[i]; if (i % 2 == 1) { current = -current; } sum = sum + current; sum2 = sum2 - current; if (sum < 0) { sum = 0; } if (sum2 < 0) { sum2 = 0; } maxSum = Math.max(maxSum, sum); maxSum = Math.max(maxSum, sum2); } return maxSum; } public static void main(String[] args) { Functions fun = new Functions(); Scanner input = new Scanner(System.in); int n = input.nextInt(); long [] array = new long [n]; for (int i = 0; i<n;i++) array[i] = input.nextInt(); long res = fun.fun(n,array); System.out.println(res); } }
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 math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) N = int(input()) A= [0] +alele() l = 1 Ans= -1e15 temp = -1e15 for i in range(1,N): z = (abs(A[i] - A[i+1]))*((-1)**(i-l)) temp = max(z,temp + z) Ans = max(Ans,temp) temp = -1e15 l = 2 temp = -1e15 for i in range(2,N): z = (abs(A[i] - A[i+1]))*((-1)**(i-l)) temp = max(z,temp + z) Ans = max(Ans,temp) print(Ans)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; long long int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; long long int f[n - 1]; for (int i = 0; i < n - 1; i++) f[i] = (i % 2) ? abs(a[i + 1] - a[i]) : -abs(a[i + 1] - a[i]); long long int sum = 0, mx = -1e9; for (int i = 0; i < n - 1; i++) { sum += f[i]; if (sum < 0) sum = 0; mx = max(sum, mx); } sum = 0; for (int i = 0; i < n - 1; i++) { sum -= f[i]; if (sum < 0) sum = 0; mx = max(mx, sum); } 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; const int inf = 0x3f3f3f3f; int a[100005]; long long dp1[100005], dp2[100005]; int a1[100005], a2[100005]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i < n; i++) { if (i % 2) { a1[i] = abs(a[i] - a[i + 1]); a2[i] = -a1[i]; } else { a1[i] = -abs(a[i] - a[i + 1]); a2[i] = -a1[i]; } } long long maxx = -inf; for (int i = 1; i < n; i++) { if (dp1[i - 1] + a1[i] < 0) dp1[i] = 0; else dp1[i] = dp1[i - 1] + a1[i]; maxx = max(dp1[i], maxx); } for (int i = 1; i < n; i++) { if (dp2[i - 1] + a2[i] < 0) dp2[i] = 0; else dp2[i] = dp2[i - 1] + a2[i]; maxx = max(dp2[i], maxx); } printf("%I64d\n", maxx); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int n, b[100004], c[100004], a[100003]; long long res1, res2, sum1, sum2; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 1; i < n; i++) { if (i & 1) b[i] = abs(a[i] - a[i + 1]), c[i] = -1 * abs(a[i] - a[i + 1]); else b[i] = -1 * abs(a[i] - a[i + 1]), c[i] = abs(a[i] - a[i + 1]); sum1 += b[i]; res1 = max(sum1, res1); sum1 = max(sum1, 0ll); sum2 += c[i]; res2 = max(sum2, res2); sum2 = max(sum2, 0ll); } cout << max(res1, res2); }
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.lang.*; public class fagain { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = sc.nextInt(); } long[] a = new long[n - 1]; for (int i = 0; i < n - 1; i++) { a[i] = (long)(Math.abs(array[i] - array[i + 1])); } long max = a[0]; long x = a[0]; long y = 0; for (int i = 1; i < n - 1; i++) { if (i % 2 == 0) { x += a[i]; y -= a[i]; if (y < 0) { y = 0; } if (x > max) { max = x; } } else { x -= a[i]; y += a[i]; if (x < 0) { x = 0; } if (y > max) { max = y; } } } System.out.println(max); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> #pragma GCC optimize(2) using namespace std; const int INF = 1e9 + 7; const int N = 2e5 + 7; const int M = 1e6 + 7; long long a[N], b[N]; long long dp[N][2]; signed main() { ios::sync_with_stdio(false); int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; if (i > 1) b[i - 1] = abs(a[i] - a[i - 1]); } for (int i = 1; i <= n; i++) { dp[i][0] = max(dp[i - 1][1] + b[i], b[i]); dp[i][1] = max(dp[i - 1][0] - b[i], 0ll); } long long ans = 0; for (int i = 1; i < n; i++) ans = max(ans, max(dp[i][0], dp[i][1])); 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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long[] a = in.readLongArray(n); long[] diff = new long[n - 1]; for (int i = 0; i < n - 1; i++) { diff[i] = Math.abs(a[i] - a[i + 1]); } long sum = 0; long sum2 = 0; long maxSum = 0; for (int i = 0; i < n - 1; i++) { long current = diff[i]; if (i % 2 == 1) { current = -current; } sum += current; sum2 -= current; if (sum < 0) { sum = 0; } if (sum2 < 0) { sum2 = 0; } maxSum = Math.max(maxSum, sum); maxSum = Math.max(maxSum, sum2); } out.println(maxSum); } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public long[] readLongArray(int n) { long[] ar = new long[n]; for (int i = 0; i < n; i++) { ar[i] = nextLong(); } return ar; } public String next() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); //tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter } } catch (IOException ex) { System.err.println("An IOException was caught :" + ex.getMessage()); } return tok.nextToken(); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.util.*; public class div407C { BufferedReader in; PrintWriter ob; StringTokenizer st; public static void main(String[] args) throws IOException { new div407C().run(); } void run() throws IOException { //in=new BufferedReader(new FileReader("input.txt")); in=new BufferedReader(new InputStreamReader(System.in)); ob=new PrintWriter(System.out); solve(); ob.flush(); } void solve() throws IOException { int n = ni(); long a[]=new long[n+1]; long b[]=new long[n]; for (int i=1; i<=n ; i++ ) { a[i] = ni(); } for (int i=1; i<n ; i++ ) { b[i] = Math.abs(a[i] - a[i+1]); } // + - + - long ans = 0 , sum=0 ; for (int i=1 ; i<n ; i++ ) { if(i%2==1) { sum = sum + b[i]; ans = Math.max( ans , sum ); sum = Math.max( sum , b[i]); ans = Math.max( ans , sum ); } else { sum = sum - b[i]; ans = Math.max( ans , sum ); } } sum = 0; for (int i=2; i<n ; i++ ) { if(i%2==0) { sum = sum + b[i]; ans = Math.max( ans , sum ); sum = Math.max( sum , b[i]); ans = Math.max( ans , sum ); } else { sum = sum - b[i]; ans = Math.max( ans , sum ); } } ob.println(ans); } String ns() throws IOException { return nextToken(); } long nl() throws IOException { return Long.parseLong(nextToken()); } int ni() throws IOException { return Integer.parseInt(nextToken()); } double nd() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { if(st==null || !st.hasMoreTokens()) st=new StringTokenizer(in.readLine()); return st.nextToken(); } int[] nia(int start,int b) throws IOException { int a[]=new int[b]; for(int i=start;i<b;i++) a[i]=ni(); return a; } long[] nla(int start,int n) throws IOException { long a[]=new long[n]; for (int i=start; i<n ;i++ ) { a[i]=nl(); } return a; } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.Scanner; public class FunctionsAgain { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] arr = new int[n]; long[] evensum = new long[n-1]; long[] oddsum = new long[n-1]; for(int i = 0; i < n; i++){ arr[i] = scan.nextInt(); } for(int i = 0; i < n-1; i++){ evensum[i] = Math.abs(arr[i+1]-arr[i]); if(i % 2 == 1) evensum[i] *= -1; oddsum[i] = evensum[i] * -1; } long sum = 0; long min = 0; long max1 = Long.MIN_VALUE; long max2 = Long.MIN_VALUE; for(int i = 0; i < n-1; i++){ sum += evensum[i]; if(sum < min){ min = sum; max1 = Math.max(max1, evensum[i]); } else{ max1 = Math.max(max1, sum-min); } } sum = 0; min = 0; for(int i = 1; i < n-1; i++){ sum += oddsum[i]; if(sum < min){ min = sum; max2 = Math.max(max2, oddsum[i]); } else{ max2 = Math.max(max2, sum-min); } } System.out.println(Math.max(max1, max2)); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> inline long long llabs(long long x) { return x < 0 ? -x : x; } long long b[100000], m = 0; int n; void dp() { long long sum = 0; for (int i = 0; i < n; i++) { sum += b[i]; if (sum < 0) { sum = 0; continue; } if (b[i] > 0) m = m > sum ? m : sum; } } int main() { scanf("%d", &n); long long num, last; scanf("%I64d", &last); n--; for (int i = 0; i < n; i++) { scanf("%I64d", &num); b[i] = (i & 1 ? -1 : 1) * llabs(num - last); last = num; } dp(); for (int i = 0; i < n; i++) b[i] = -b[i]; dp(); printf("%I64d", m); 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
#!/usr/bin/python # coding: utf-8 n=int(raw_input()) arr=map(long,raw_input().split(' ')) arr1=[] for i in xrange(n-1): tmp=abs(arr[i+1]-arr[i]) tmp=tmp*((-1)**i) arr1.append(tmp) arr2=[] for i in xrange(n-1): arr2.append(arr1[i]*(-1)) max=current=0 for i in xrange(n-1): current+=arr1[i] if(current<0): current=0 if(max<current): max=current current=0 for i in xrange(n-1): current+=arr2[i] if(current<0): current=0 if(max<current): max=current print max ''' 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: Functions_again.png 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 ≀ 10^5) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-10^9 ≀ ai ≀ 10^9) β€” 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. '''
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class Main{ public static int f(int[] a,int l,int r){ int sum = 0; for(int i = l;i<r;i++){ int num = Math.abs(a[i] - a[i + 1]) * ((i - l) % 2 == 0 ? 1 : -1); System.out.println(num); sum+= num; } return sum; } public static long getAns(int[] s,int n){ long[] dp = new long[n]; for(int i = 1;i<n;i++){ dp[i] = Math.max(dp[i-1]+s[i],s[i]); } long max = dp[0]; for(int i = 1;i<n;i++){ // System.out.println("dp[i]:"+dp[i]); if(max<dp[i]) max = dp[i]; } return max; } public static void init(int[] a,int[] s,int[] sr,int n){ for(int i = 1;i<n;i++){ int num = Math.abs(a[i] - a[i + 1]) * ((i - 1) % 2 == 0 ? 1 : -1); s[i]= num; sr[i]= -num; } } public static void main(String[] args) throws FileNotFoundException { // File file = new File("C:/oy/input.txt"); // FileInputStream in = new FileInputStream(file); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n+1]; for(int i = 1;i<=n;i++){ a[i] = scanner.nextInt(); } int[] s = new int[n]; int[] sr = new int[n]; init(a,s,sr,n); System.out.println(Math.max(getAns(s,n),getAns(sr,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.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class c { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long[] arr = new long[n]; for(int i = 0; i < n; i++) arr[i] = in.nextLong(); long[] vals1 = new long[n]; long[] vals2 = new long[n]; for(int i = 0; i < n - 1; i++) { vals1[i] = Math.abs(arr[i] - arr[i + 1]); if(i % 2 == 1) vals1[i] *= -1; vals2[i] = -vals1[i]; } long max = 0; long sum = 0; for(int i = 0; i < n - 1; i++) { sum = Math.max(sum, 0); sum += vals1[i]; max = Math.max(max, sum); } sum = 0; for(int i = 0; i < n - 1; i++) { sum = Math.max(sum, 0); sum += vals2[i]; max = Math.max(max, sum); } System.out.println(max); } //@ static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) return st.nextToken(); else st = new StringTokenizer(br.readLine()); return next(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } //# public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { 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(input()) a=list(map(int, input().split())) arr=[abs(a[i]-a[i+1])*(-1)**i for i in range(n-1)] maximum=0 summ=0 for j in arr: if j>0 or abs(j)<abs(summ): summ+=j else: summ=0 maximum=max(maximum, abs(summ)) summ=0 for k in arr[1:]: if k<0 or abs(k)<abs(summ): summ+=k else: summ=0 maximum=max(maximum, abs(summ)) print(maximum)
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 n, a1, a2, c, b, t, y, d; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> a1; while (--n) { cin >> a2; b = abs(a1 - a2); a1 = a2; t = c; c = max(b, d + b); y = max(y, c); d = t - b; } cout << y; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; const long long mod = 1e9 + 7; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3fLL; long long a[N], b[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; long long ans = -INF, sum = 0; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 1; i <= n - 1; i++) { b[i] = abs(a[i] - a[i + 1]); } for (int i = 1; i <= n - 1; i++) { long long p; if (i % 2) p = -1; else p = 1; p = p * b[i]; if (sum + p >= 0) { sum += p; } else { sum = 0; } ans = max(ans, sum); } sum = 0; for (int i = 1; i <= n - 1; i++) { long long p; if (i % 2) p = 1; else p = -1; p = p * b[i]; if (sum + p >= 0) { sum += p; } else { sum = 0; } ans = max(ans, sum); } 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; int main() { long long i, n; cin >> n; long long a[100005], alpha[100005], bravo[100005]; for (i = 0; i < n; i++) scanf("%lld", &a[i]); for (i = 0; i < n - 1; i++) { if (i == 0 || i % 2 == 0) { alpha[i] = abs(a[i] - a[i + 1]); bravo[i] = -1 * abs(a[i] - a[i + 1]); } else { alpha[i] = -1 * abs(a[i] - a[i + 1]); bravo[i] = abs(a[i] - a[i + 1]); } } long long alpha1 = 0, bravo1 = 0; for (i = 0; i < n - 1; i++) { alpha1 = max(alpha[i], alpha1 + alpha[i]); bravo1 = max(bravo1, alpha1); } long long alpha2 = 0, bravo2 = 0; for (i = 0; i < n - 1; i++) { alpha2 = max(bravo[i], alpha2 + bravo[i]); bravo2 = max(bravo2, alpha2); } printf("%lld\n", max(bravo1, bravo2)); }
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 n = int(stdin.readline()) def sub(a): ans = 0 cur = 0 for i in a: cur += i if cur < 0: cur = i if cur < 0: cur = 0 ans = max(ans,cur) return ans a = map(int,stdin.readline().split()) b = [] c = [] for i in xrange(n-1): x = a[i] - a[i+1] if x < 0: x = -x if i%2: b.append(x);c.append(-x) else: b.append(-x);c.append(x) print max(sub(b),sub(c))
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
//package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) throws IOException { // write your code here Scanner s = new Scanner(System.in); // BufferedReader s=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int n=s.nextInt();Long[] a=new Long[n]; for(int i=0;i<n;i++){ a[i]=s.nextLong(); }max=Long.MIN_VALUE;Long[] []dp=new Long[n][2]; for(int i=0;i<n-1;i++){ if(i==0){ dp[i][1]=Math.abs(a[i]-a[i+1]);dp[i][0]=0L; }else{ dp[i][1]=dp[i-1][0]+Math.abs(a[i]-a[i+1]); dp[i][0]=Math.max(0,dp[i-1][1]-Math.abs(a[i]-a[i+1])); }max=Math.max(max,dp[i][1]); } System.out.println(max); } static double power(double x, long y, int p) { double res = 1; x = x % p; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int m; static int n; static int path = Integer.MAX_VALUE; static int got = 0; static Long[] sum;static Long[] a; public static long dfs(int i, ArrayList<Integer>[] h, int[] vis) { vis[i] = 1; sum[i]+=a[i];if(h[i]==null) return sum[i]; for (Integer j : h[i]) { if (vis[j] == 0) { sum[i]+=dfs(j, h, vis); } }return sum[i]; }static long max=Long.MIN_VALUE;static long max1=Long.MIN_VALUE; public static void dfs1(int i, ArrayList<Integer>[] h, int[] vis) { vis[i] = 1;//sum[i]+=a[i]; if(h[i]==null) return ; for (Integer j : h[i]) { if (vis[ j] == 0) { if(sum[j]>max) {max1=max;max=sum[j];} else if(sum[j]>max1) max1=sum[j]; dfs1(j, h, vis); } }return ; }static long fans=Long.MIN_VALUE; public static long dfs2(int i, ArrayList<Integer>[] h, int[] vis) { long max2=Long.MIN_VALUE;long max3=Long.MIN_VALUE; vis[i] = 1;if(h[i]==null) return a[i]; for (Integer j : h[i]) { if (vis[ j] == 0) { long k= dfs2(j, h, vis); if(k>max2) { max3=max2;max2=k;} else if(k>max3) max3=k; } } // System.out.println(i+" "+max2+" "+max3+" "+sum[i]); if(max2!=Long.MIN_VALUE&&max3!=Long.MIN_VALUE&&max2+max3> fans) fans=max2+max3; // if(i==1) return max2; return Math.max(sum[i],max2); } public static void bfs(int i, HashMap<Integer, Integer>[] h, int[] vis, int len, int papa) { Queue<Integer> q = new LinkedList<Integer>(); q.add(i); } static int i(String a){ return Integer.parseInt(a); }static long l(String a){ return Long.parseLong(a); }static String[] inp() throws IOException{ BufferedReader s=new BufferedReader(new InputStreamReader(System.in)); return s.readLine().trim().split("\\s+"); } } class Student { int t,l,r; // String name, address; // Constructor public Student(int t,int r) {this.t=t; this.r=r; } // Used to print student details in main() public String toString() { return this.t + " " +this.l+" "+this.r; } } class Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.t-b.t; } }
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 max_subarray(A): max_ending_here = max_so_far = A[0] for x in A[1:]: max_ending_here = max(x, max_ending_here + x) max_so_far = max(max_so_far, max_ending_here) return max_so_far n = int(input()) a = [int(v) for v in input().split()] b = [abs(a[i]-a[i+1])*(-1)**i for i in range(n-1)] print(max(max_subarray(b), max_subarray([-v for v in 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
n = int(input()) num = list(map(int, input().split())) diff = [abs(j-i) for i, j in zip(num, num[1:])] s1 = 0 s2 = 0 m1 = 0 m2 = 0 for i, x in enumerate(diff): if s1 < 0: s1 = 0 if s2 < 0: s2 = 0 if i % 2 == 0: s1 += x s2 -= x else: s1 -= x s2 += x if s1 > m1: m1 = s1 if s2 > m2: 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
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class C_407 { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); int n = Integer.parseInt(input.readLine()); int[] nums = new int[n]; String[] line = input.readLine().split(" "); for (int i = 0; i < n; i++) { nums[i] = Integer.parseInt(line[i]); } long max = 0; long sum = 0; long tmp; boolean neg = false; for (int i = 0; i < n - 1; i++) { tmp = Math.abs(nums[i] - nums[i + 1]); tmp = (neg) ? -tmp : tmp; sum += tmp; sum = Math.max(sum, 0); max = Math.max(max, sum); neg = !neg; } sum = 0; neg = false; for (int i = 1; i < n - 1; i++) { tmp = Math.abs(nums[i] - nums[i + 1]); tmp = (neg) ? -tmp : tmp; sum += tmp; sum = Math.max(sum, 0); max = Math.max(max, sum); neg = !neg; } System.out.println(max); input.close(); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.Scanner; public class FunctionsAgain { public static void main(String[] args) { try (Scanner s = new Scanner(System.in)) { int n = s.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } // Store the best negative and positive function value starting at the index to // the right. long previousBestNeg = 0; long previousBestPos = 0; long best = 0; for (int i = n - 2; i >= 0; i--) { int absDifference = Math.abs(a[i] - a[i + 1]); long tempBestNeg = -absDifference; long tempBestPos = absDifference; if (i < n - 2) { if (previousBestNeg > 0) { tempBestPos += previousBestNeg; } if (previousBestPos > 0) { tempBestNeg += previousBestPos; } } previousBestNeg = tempBestNeg; previousBestPos = tempBestPos; best = Math.max(best, previousBestPos); } System.out.println(best); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.text.*; public class Prac{ 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 ni() { 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 nl() { 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[] nia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String rs() { 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; } } public static class Key { private final int x; private final int y; public Key(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Key)) return false; Key key = (Key) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } static PrintWriter w = new PrintWriter(System.out); static long mod=998244353L,mod1=1000000007; static long kadane(long arr[]){ long maxC=0,maxSoF=Long.MIN_VALUE; int n=arr.length; for(int i=0;i<n;i++){ maxC+=arr[i]; maxSoF=Math.max(maxSoF,maxC); maxC=Math.max(0,maxC); } return maxSoF; } public static void main (String[] args)throws IOException{ InputReader sc=new InputReader(System.in); int n=sc.ni(); long arr[]=new long[n]; for(int i=0;i<n;i++)arr[i]=sc.ni(); long temp[]=new long[n]; long temp1[]=new long[n]; long temp2[]=new long[n]; for(int i=1;i<n;i++){ temp[i-1]=Math.abs(arr[i]-arr[i-1]); if(i%2==0){ temp1[i-1]=-temp[i-1]; temp2[i-1]=temp[i-1]; } else { temp2[i-1]=-temp[i-1]; temp1[i-1]=temp[i-1]; } } w.println(Math.max(kadane(temp1),kadane(temp2))); w.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_n = 200005; long long b, a, dp1[max_n], dp2[max_n]; int n; int main() { cin >> n; cin >> a; int f = 1; for (int i = 1; i < n; ++i) { cin >> b; dp1[i - 1] = abs(a - b) * f; dp2[i - 1] = abs(a - b) * (-f); f = -f; a = b; } long long mx = dp1[0]; long long tol = 0; for (int i = 0; i < n - 1; ++i) { tol += dp1[i]; if (tol > mx) { mx = tol; } if (tol < 0) { tol = 0; } } long long mx2 = dp2[0]; tol = 0; for (int i = 0; i < n - 1; ++i) { tol += dp2[i]; if (tol > mx2) { mx2 = tol; } if (tol < 0) { tol = 0; } } cout << max(mx, mx2); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author wannabe */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public long maxSubArray(long[] A) { if (A.length == 0) return -1; long max = A[0]; long[] sum = new long[A.length]; sum[0] = A[0]; for (int i = 1; i < A.length; i++) { sum[i] = Math.max(A[i], sum[i - 1] + A[i]); max = Math.max(max, sum[i]); } return max; } public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); long[] numbers = new long[n]; for (int i = 0; i < numbers.length; i++) { numbers[i] = in.nextLong(); } long[] diffsEven = new long[n - 1]; long[] diffsOdd = new long[n - 2]; for (int i = 0; i < numbers.length - 1; i++) { diffsEven[i] = Math.abs(numbers[i] - numbers[i + 1]) * (long) Math.pow(-1, i); if (i == 0) continue; diffsOdd[i - 1] = -1 * diffsEven[i]; } out.print(Math.max(maxSubArray(diffsEven), maxSubArray(diffsOdd))); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.ObjectInputStream.GetField; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; public class Q2 { static long MOD = 1000000007; static boolean b1,b[],bc[]; static boolean boo[][][]; static int ans1 = -1,ans2 = -1, root; static ArrayList<Integer>[] amp,amp1; static ArrayList<Pair>[] pmp; static int sum[],dist[],cnt[],ans[],size[],col[][]; static int p = 0,cnt1 =0 ,cnt2 = 0; //static ArrayList<Pair3>[][][] pmp; static FasterScanner sc = new FasterScanner(System.in); static Queue<Integer> q = new LinkedList<>(); static int arr[],start[],end[],color[],parent[]; static PriorityQueue<Integer> pq; //static ArrayList<Integer> parent = new ArrayList<>(); static LinkedList<Integer> fa; static BufferedWriter log; static TreeMap<Integer,Integer> tm = new TreeMap<>(); // static HashMap<Integer,Pair> hs; static Stack<Integer> stack = new Stack<>(); static Pair prr[]; static int dp[][]; static long parent1[],parent2[],size1[],size2[],value[]; static long Ans; public static void main(String[] args) throws Exception { /*new Thread(null, new Runnable() { public void run() { try { soln(); } catch (Exception e) { System.out.println(e); } } }, "1", 1 << 26).start();*/ soln(); } static int MAX = 1000005; static int n , m ,k, max, x1, x2; static HashSet<Pair> hs; static double DP[][][]; public static void soln() throws IOException { //FasterScanner in = new FasterScanner(new FileInputStream("C:\\Users\\Admin\\Desktop\\QAL.txt")); //PrintWriter out = new PrintWriter("C:\\Users\\Admin\\Desktop\\A1.txt"); log = new BufferedWriter(new OutputStreamWriter(System.out)); int n = sc.nextInt(); int arr[] = sc.nextIntArray(n); long arr1[] = new long[n-1]; long arr2[] = new long[n-1]; int j = 1; for(int i = 0; i< n-1; i++){ arr1[i] = 1L*Math.abs(arr[i]-arr[i+1])*j; j*=-1; } for(int i =0 ;i< n-1 ;i ++) arr2[i] = -arr1[i]; System.out.println(Math.max(maxSubArraySum(arr1), maxSubArraySum(arr2))); log.close(); //out.close(); } static long maxSubArraySum(long a[]) { int size = a.length; long max_so_far = Long.MIN_VALUE/2, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } public class TrieNode{ TrieNode[] t = new TrieNode[2]; int cnt = 0; } public class Trie{ TrieNode root; Trie(){ root = new TrieNode(); } public void insert(String s){ TrieNode temp = root; for(int i = 0; i< s.length();i++){ if(temp.t[s.charAt(i)-'0']==null){ TrieNode n = new TrieNode(); temp.t[s.charAt(i)-'0'] = n; } temp = temp.t[s.charAt(i)-'0']; } temp.cnt++; } public void delete(String s, TrieNode temp){ } public String get(String s){ StringBuilder sb = new StringBuilder(); TrieNode temp = root; for(int i = 0; i< s.length();i++){ int x = (s.charAt(i)-'0'+1)%2; if(temp.t[x]!=null){ temp = temp.t[x]; sb.append(1); } else{ temp = temp.t[(x+1)%2]; sb.append(0); } } return sb.toString(); } } public static class FenwickTree { int[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new int[size + 1]; } public int rsq(int ind) { assert ind > 0; int sum = 0; while (ind > 0) { sum += array[ind];ind -= ind & (-ind); } return sum; } public int rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, int value) { assert ind > 0; while (ind < array.length) { array[ind] += value; ind += ind & (-ind); } } public int size() { return array.length - 1; } } public static void dfs(int x){ b[x] = true; for(int e:amp[x]){ if(!b[e]){ dfs(e); } } } public static void bfs(int x){ b[x] = true; q = new LinkedList<Integer>(); q.add(x); while(!q.isEmpty()){ //System.out.println(q); int y = q.poll(); for(int i:amp[y]){ if(!b[i]){ q.add(i); dist[i] = Math.max(dist[i], dist[y]+1); if(dist[i]>max){ max = dist[i]; k = i; } b[i]= true; } } } } static class Pair implements Comparable<Pair> { int u; int v; public Pair(){ u = 0; v = 0; } public Pair(int u, int v) { this.u = u; this.v = v; } 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 Long.compare(u, other.u) != 0 ? (Long.compare(u, other.u)) : (Long.compare(v, other.v)); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static int gcd(int n, int m){ if(m!=0) return gcd(m,n%m); else return n; } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l)/2; if (A[m]>=key) r = m; else l = m; } return r; } /* public static Pair recur(int N, int K, int C){ if(K>k) return new Pair(Long.MAX_VALUE/2,-1); if(N>=n && k<K) return new Pair(Long.MAX_VALUE/2,-1); if(N>=n && k==K) return new Pair(0,k); if(N>=n) return new Pair(0,0); if(dp[N][C][K]!=null){ //System.out.println(dp[N][C][K]); return dp[N][C][K]; } Pair ans = new Pair(Long.MAX_VALUE/2,-1); if(arr[N]>0){ Pair p; if(arr[N]==C) p = recur(N+1,K,arr[N]); else p = recur(N+1,K+1,arr[N]); if((p.u)<ans.u){ ans = p; } if(p.u==ans.u){ if(p.v>ans.v){ ans = p; } } } else{ for(int i = 1 ;i <= m; i++){ Pair p; if(i==C) p = recur(N+1,K,i); else p = recur(N+1,K+1,i); p.u+=col[N][i-1]; if((p.u)<ans.u){ ans = p; } if(p.u==ans.u){ if(p.v>ans.v){ ans = p; } } } //System.out.println(ans); } return dp[N][C][K] = ans; }*/ public static void mergeSort(int[] arr2, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr2,l,mid); mergeSort(arr2,mid+1,r); merge(arr2,l,r,mid); //System.out.println(Ans); } } public static void merge(int arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); int left[] = new int[n1]; int right[] = new int[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ cnt[right[j]]+=(n1-i); arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static void buildGraph(int n){ for(int i =0;i<n;i++){ int x = sc.nextInt(), y = sc.nextInt(); amp[x].add(y); hs.add(new Pair(x,y)); hs.add(new Pair(y,x)); } } public static int getParent(int x){ while(parent[x]!=x){ parent[x] = parent[ parent[x]]; x = parent[ x]; } return x; } static int min(int a, int b, int c){ if(a<b && a<c) return a; if(b<c) return b; return c; } private static void permutation(String prefix, String str) { int n = str.length(); if (n == 0); //hs.add(prefix); else { for (int i = 0; i < n; i++) permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n)); } } static class Graph{ int vertex; long weight; } public static void buildTree(int n){ int arr[] = sc.nextIntArray(n); for(int i = 0;i<n;i++){ int x = arr[i]-1; amp[i+1].add(x); amp[x].add(i+1); } }/* static class SegmentTree { Pair st[]; // long lazy[]; SegmentTree(int n) { int size = 8 * n; st = new Pair[size]; for(int i = 0; i< size;i++) st[i] = new Pair(); // lazy = new long[size]; build(0, n - 1, 1); } Pair build(int ss, int se, int si) { if (ss == se) { st[si] = new Pair(); if(arr[ss]==0){ st[si].u = 1; } st[si].v = (se-ss+1)-st[si].u; st[si].z = 0; return st[si]; } int mid = (ss + se) / 2; Pair temp1 = build(ss, mid, 2*si), temp2 = build(mid+1, se, si*2+1); long a1 = temp1.u+temp2.u, a2 = temp1.v+temp2.v, a3 = temp1.z+temp2.z+temp1.u*temp2.u+temp1.v*temp2.v; return st[si] = new Pair(a1,a2,a3); } void update(int si, int ss, int se, int idx, int val) { if (ss == se) { st[si] = new Pair(); arr[idx] = val; if(arr[idx]==0){ st[si].u = 1; } st[si].v = (se-ss+1)-st[si].u; st[si].z = 0; } else { int mid = (ss + se) / 2; if(ss <= idx && idx <= mid) { update(2*si, ss, mid, idx, val); } else { update(2*si+1, mid+1, se, idx, val); } long a1 = st[si*2].u+st[si*2+1].u, a2 = st[si*2].v+st[si*2+1].v, a3 = st[si*2].z+st[si*2+1].z+st[si*2+1].u*st[si*2].u+st[si*2+1].v*st[si*2].v; st[si] = new Pair(a1,a2,a3); } } Pair get(int qs, int qe, int ss, int se, int si){ if(qs>se || qe<ss){ return new Pair(0,0,0); } if (qs <= ss && qe >= se) { return st[si]; } int mid = (ss+se)/2; Pair temp1 = get(qs, qe, ss, mid, si * 2), temp2 = get(qs, qe, mid + 1, se, si * 2 + 1); long a1 = temp1.u+temp2.u, a2 = temp1.v+temp2.v, a3 = temp1.z+temp2.z+temp1.u*temp2.u+temp1.v*temp2.v; st[si] = new Pair(a1,a2,a3); return st[si]; } /*void updateRange(int node, int start, int end, int l, int r, long val) { if(lazy[node] != 0) { // This node needs to be updated st[node] += (end - start + 1) * lazy[node]; // Update it if(start != end) { lazy[node*2] += lazy[node]; // Mark child as lazy lazy[node*2+1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if(start > end || start > r || end < l) // Current segment is not within range [l, r] return; if(start >= l && end <= r) { // Segment is fully within range st[node] += (end - start + 1) * val; if(start != end) { // Not leaf node lazy[node*2] += val; lazy[node*2+1] += val; } return; } int mid = (start + end) / 2; updateRange(node*2, start, mid, l, r, val); // Updating left child updateRange(node*2 + 1, mid + 1, end, l, r, val); // Updating right child st[node] = st[node*2] + st[node*2+1]; // Updating root with max value } long queryRange(int node, int start, int end, int l, int r) { if(start > end || start > r || end < l) return 0L; // Out of range if(lazy[node] != 0) { // This node needs to be updated st[node] += (end - start + 1) * lazy[node]; // Update it if(start != end) { lazy[node*2] += lazy[node]; // Mark child as lazy lazy[node*2+1] += lazy[node]; // Mark child as lazy } lazy[node] = 0L; // Reset it } if(start >= l && end <= r) // Current segment is totally within range [l, r] return st[node]; int mid = (start + end) / 2; long p1 = queryRange(node*2, start, mid, l, r); // Query left child long p2 = queryRange(node*2 + 1, mid + 1, end, l, r); // Query right child return (p1 + p2); } void print() { for (int i = 0; i < st.length; i++) { System.out.print(st[i].u+" "+st[i].v+" "+st[i].z+"\n"); } System.out.println(); } }*/ static class Tree { ArrayList<Integer>[] g ; int T[]; // parent int L[]; // level int P[][]; // P[i][j] = 2^j th parent of i public Tree(int n) { T = new int[n]; L = new int[n]; P = new int[n][log2(n) + 1]; g = (ArrayList<Integer>[])new ArrayList[n]; L[0] = 0; T[0] = -1; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < n ; i++) { int a = sc.nextInt(); for(int j = 0; j<a; j++){ int b = sc.nextInt()-1; g[i].add(b); g[b].add(i); } } dfs(0, -1); for (int j = 0; (1 << j) <= n; j++) pre(0, j,-1); } public int log2(int n) { return (int) (Math.log10(n) / Math.log10(2)); } public void dfs(int node, int p) { for (int k : g[node]) { if (k != p) { T[k] = node; L[k] = L[node] + 1; dfs(k, node); } } } public void pre(int node, int j,int p) { if (j == 0) { P[node][j] = T[node]; } else { P[node][j] = P[P[node][j - 1]][j - 1]; } for (int k : g[node]) { if(k!=p) pre(k, j,node); } } public int lca(int u, int v) { if (L[u] > L[v]) { int temp = u; u = v; v = temp; } int log; for (log = 0; (1 << log) <= L[v]; log++) ; // convert level into log log--; for (int i = log; i >= 0; i--) { if ((1 << i) <= L[v] - L[u]) // make both node's level same v = P[v][i]; } if (u == v) return u; for (int i = log; i >= 0; i--) { if (P[u][i] != -1 && P[u][i] != P[v][i]) // shift up both u and v { u = P[u][i]; v = P[v][i]; } } return T[u]; } } 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; } 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 long modInverse(long a, long mOD2){ return power(a, mOD2-2, mOD2); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y/2, m) % m; p = (p * p) % m; return (y%2 == 0)? p : (x * p) % m; } static long d,x,y; public static void extendedEuclidian(long a, long b){ if(b == 0) { d = a; x = 1; y = 0; } else { extendedEuclidian(b, a%b); int temp = (int) x; x = y; y = temp - (a/b)*y; } } static class FasterScanner { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public FasterScanner(InputStream stream) { this.stream = stream; } public String nextString() { 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 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 long[] nextLongArray(int n) { long a[] = new long[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 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
def main(): input() aa = list(map(int, input().split())) a, s = aa[0], 1 u = c = mi = ma = 0 for b in aa: c += abs(a - b) * s a = b s *= -1 if ma < c: ma = c u = ma - mi elif mi > c: mi = c a, s = aa[0], -1 v = c = mi = ma = 0 for b in aa: c += abs(a - b) * s a = b s *= -1 if ma < c: ma = c v = ma - mi elif mi > c: mi = c print(max(u, v)) 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
from math import inf n=int(input()) a=list(map(int,input().split())) b=[] for i in range(len(a)-1): b.append(abs(a[i]-a[i+1])) mini=-inf dp=[[0 for i in range(2)]for j in range(len(b))] dp[0][0]=b[0] dp[0][1]=0 for i in range(1,len(b)): dp[i][0]=max(dp[i-1][1]+b[i],b[i]) dp[i][1]=dp[i-1][0]-b[i] ##print(b) ##print(dp) maxi=-inf for i in range(len(b)): maxi=max(maxi,max(dp[i][0],dp[i][1])) print(maxi)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long a[100004]; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; long long count = 0, m = abs(a[1] - a[2]); int s = 1; for (int i = 1; i <= n - 1; i++) { count += abs(a[i] - a[i + 1]) * s; s *= -1; m = max(m, count); if (count < 0) { count = 0; s = 1; continue; } } count = 0; s = 1; for (int i = 2; i <= n - 1; i++) { count += abs(a[i] - a[i + 1]) * s; s *= -1; m = max(m, count); if (count < 0) { count = 0; s = 1; continue; } } cout << m << 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; inline int read() { int s = 0, t = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') t = -1; c = getchar(); } while (isdigit(c)) s = s * 10 + c - 48, c = getchar(); return s * t; } const int N = 1e5 + 5; const long long inf = 1e16; long long f[N][2]; int v[N]; inline long long Abs(long long x) { return x >= 0 ? x : -x; } inline void Max(long long &x, long long v) { if (v > x) x = v; } int main() { int n = read(); long long ans = 0; for (register int i = 1; i <= n; i++) v[i] = read(), f[i][0] = f[i][1] = -inf; for (register int i = 2; i <= n; i++) { if (!(i & 1)) { Max(f[i][0], f[i - 1][0] + Abs(v[i] - v[i - 1])); Max(f[i][1], f[i - 1][1] - Abs(v[i] - v[i - 1])); Max(f[i][0], Abs(v[i] - v[i - 1])); } else { Max(f[i][1], f[i - 1][1] + Abs(v[i] - v[i - 1])); Max(f[i][0], f[i - 1][0] - Abs(v[i] - v[i - 1])); Max(f[i][1], Abs(v[i] - v[i - 1])); } Max(ans, f[i][0]), Max(ans, f[i][1]); } cout << ans << endl; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; template <class T> using min_queue = priority_queue<T, vector<T>, greater<T>>; template <typename Args> void kill(Args args) { cout << args << "\n"; exit(0); } const double PI = acos(-1); const long long MOD = 1000000007; const int INF = 0x3f3f3f3f; const long long LLINF = 0x3f3f3f3f3f3f3f3f; const int N = 101010; long long arr[N]; long long temp[N]; long long ans = -LLINF; int n; void solve(int testnum) { cin >> n; for (int i = 1; i <= n; i++) { cin >> arr[i]; } for (int i = 1; i < n; i++) { temp[i] = abs(arr[i] - arr[i + 1]); if (!(i & 1)) temp[i] *= -1; } long long pref = 0; long long maxx = -LLINF; for (int i = 1; i < n; i++) { pref += temp[i]; maxx = max(maxx, pref); if (pref < 0) pref = 0; } if (n == 2) kill(maxx); temp[1] = 0; for (int i = 1; i < n - 1; i++) { temp[i] = temp[i + 1]; temp[i] *= -1; } pref = 0; for (int i = 1; i < n - 1; i++) { pref += temp[i]; maxx = max(maxx, pref); if (pref < 0) pref = 0; } cout << maxx << "\n"; } void precompute() {} int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << fixed << setprecision(12); int testcase = 1; clock_t zzzx = clock(); precompute(); for (int i = 1; i <= testcase; i++) { solve(i); } double elapsed_time = (double)(clock() - zzzx) / CLOCKS_PER_SEC; cerr << "elapsed_time" << " = " << (elapsed_time) << "\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; long long a[100005]; long long b[100005]; long long c[100005]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%I64d", &a[i]); for (int i = 1; i < n; i++) { b[i] = a[i + 1] - a[i]; if (b[i] < 0) b[i] = -b[i]; } c[0] = 0ll; for (int i = 1; i < n; i++) { if (i % 2) c[i] = c[i - 1] + b[i]; else c[i] = c[i - 1] - b[i]; } sort(c, c + n); printf("%I64d\n", c[n - 1] - c[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; int main() { ios::sync_with_stdio(false); int i, j, k, t, c, n; cin >> n; int a[n]; int b[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]); } long long ans = 0; long long sum = 0; for (i = 0; i < n - 1; i++) { if (i % 2) { sum -= b[i]; } else sum += b[i]; if (sum < 0) sum = 0; if (sum > ans) ans = sum; } sum = 0; for (i = 1; i < n - 1; i++) { if (i % 2 == 0) { sum -= b[i]; } else sum += b[i]; if (sum < 0) sum = 0; if (sum > ans) ans = sum; } 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
from sys import stdin,stdout # stdin = open("input.txt" , "r") # stdout = open("output.txt", "w") n = int(stdin.readline().strip()) arr = list(map(int,stdin.readline().strip().split(' '))) tarr1 = [abs(arr[1]-arr[0])] tarr2 = [] for i in range(2,n): tarr1.append(pow(-1,i-1)*abs(arr[i]-arr[i-1])) tarr2.append(-1*tarr1[-1]) ans = tarr1[0] tans =tarr1[0] for i in tarr1[1:]: if tans<0: tans=i else: tans+=i ans=max(tans,ans) if len(tarr2)>0: tans=tarr2[0] ans=max(ans,tans) for i in tarr2[1:]: if tans<0: tans=i else: tans+=i ans=max(tans,ans) stdout.write(str(ans)+"\n")
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 long long LLINF = LLONG_MAX; const int INF = INT_MAX; const int MAXN = 1e5 + 10; int n; long long a[MAXN]; long long b[MAXN], c[MAXN]; long long F(long long* a) { long long ret = -LLINF, curr = 0; for (int i = 0; i < n - 1; i++) { curr += a[i]; if (curr > ret) ret = curr; if (curr < 0) curr = 0; } return ret; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%I64d", &a[i]); for (int i = 0; i < n - 1; i++) b[i] = c[i] = abs(a[i] - a[i + 1]); for (int i = 0; i < n - 1; i++) { if (i & 1) c[i] = -c[i]; else b[i] = -b[i]; } cout << max(F(b), F(c)) << 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 sys def read_ints(): return [int(x) for x in sys.stdin.readline().strip().split()] def main(): N = read_ints()[0] a = read_ints() nums = [abs(a[i] - a[i + 1]) for i in range(N - 1)] N -= 1 odd = [0] * N even = [0] * N odd[0] = nums[0] for ix in range(1, N): odd[ix] = max(nums[ix], even[ix - 1] + nums[ix]) even[ix] = odd[ix - 1] - nums[ix] print(max(max(odd), max(even))) if __name__ == '__main__': main()
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st; int n = Integer.parseInt(bf.readLine()); int arr[] = new int[n]; st = new StringTokenizer(bf.readLine()); for (int i = 0; i < arr.length; i++) arr[i] = Integer.parseInt(st.nextToken()); for (int i = 0; i < arr.length - 1; i++) arr[i] = Math.abs(arr[i] - arr[i + 1]); int start_even[] = new int[n]; int start_odd[] = new int[n]; for (int i = 0; i < start_odd.length; i++) { if (i % 2 == 0) start_even[i] = arr[i]; else start_even[i] = -arr[i]; start_odd[i] = -start_even[i]; } long sum = 0, max = 0; for (int i = 0; i < start_odd.length-1; i++) { sum += start_even[i]; max = Math.max(max, sum); if (sum < 0) sum = 0; } sum = 0; for (int i = 0; i < start_odd.length-1; i++) { sum += start_odd[i]; max = Math.max(max, sum); if (sum < 0) sum = 0; } out.println(max); out.flush(); 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> const long long mod = 1000 * 1000 * 1000 + 7; const long long mod1 = 998244353; const long long INF = 1ll * 1000 * 1000 * 1000 * 1000 * 1000 * 1000 + 7; using namespace std; long long power(long long x, long long y) { long long res = 1; while (y > 0) { if (y & 1) res = (long long)(res * x); y = y >> 1; if (x <= 100000000) x = (long long)(x * x); } return res; } long long sub_sum(long long a[], long long n) { long long ans = a[0], sum = 0, min_sum = 0; for (int r = 0; r < n; ++r) { sum += a[r]; ans = max(ans, sum - min_sum); min_sum = min(min_sum, sum); } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n; cin >> n; long long a[n]; long long b[n - 1]; long long c[n - 1]; for (int(i) = (0); (i) < (n); ++(i)) cin >> a[i]; for (int i = 0; i < n - 1; i++) { long long x = abs(a[i] - a[i + 1]); if (i & 1) { b[i] = x; c[i] = -x; } else { b[i] = -x; c[i] = x; } } long long ans = max(sub_sum(b, n - 1), sub_sum(c, n - 1)); cout << ans; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import math def inp(): return int(raw_input().strip()) def inp_s(): return raw_input().strip() def inp_arr(): return map(long, raw_input().strip().split()) 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 = inp() arr = inp_arr() arr1 = [0] * n for i in xrange(n - 1): k = -1 if i % 2 == 1 else 1 arr1[i] = abs(arr[i] - arr[i + 1]) * k * (-1) arr[i] = abs(arr[i] - arr[i + 1]) * k arr.pop() arr1.pop() # print arr # print arr1 print max(maxSubArraySum(arr, n - 1), maxSubArraySum(arr1, n - 1))
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long int kadanes(long long int* arr, long long int n) { long long int max_so_far = arr[0], sum = arr[0]; for (long long int i = 1; i < n; i++) { sum = max(sum + arr[i], arr[i]); max_so_far = max(max_so_far, sum); } return max_so_far; } void solve() { long long int i, j, n; cin >> n; long long int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; long long int* p = new long long int[n - 1]; long long int* q = new long long int[n - 1]; for (i = 0; i < n - 1; i++) { long long int diff = abs(arr[i + 1] - arr[i]); if (i % 2 == 0) { p[i] = diff; q[i] = -diff; } else { p[i] = -diff; q[i] = diff; } } long long int ans = max(kadanes(p, n - 1), kadanes(q, n - 1)); cout << ans << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long int t; t = 1; while (t--) { 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
# target Expert # Author : raj1307 - Raj Singh # Date : 25.07.19 from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(100000000) threading.stack_size(40960000) thread = threading.Thread(target=main) thread.start() #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace #from math import ceil,floor,log,sqrt,factorial,pow,pi #from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right #from decimal import *,threading #from itertools import permutations abc='abcdefghijklmnopqrstuvwxyz' abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25} mod=1000000007 #mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def getKey(item): return item[0] def sort2(l):return sorted(l, key=getKey) def d2(n,m,num):return [[num for x in range(m)] for y in range(n)] def isPowerOfTwo (x): return (x and (not(x & (x - 1))) ) def decimalToBinary(n): return bin(n).replace("0b","") def ntl(n):return [int(i) for i in str(n)] def powerMod(x,y,p): res = 1 x %= p while y > 0: if y&1: res = (res*x)%p y = y>>1 x = (x*x)%p return res def gcd(x, y): while y: x, y = y, x % y return x def isPrime(n) : # Check Prime Number or not if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def read(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') def maxSubArraySum(a, size): max_so_far = -inf - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far def main(): #for _ in range(ii()): n=ii() l=li() x=[] y=[] f=1 g=-1 for i in range(n-1): x.append(abs(l[i]-l[i+1])*f) y.append(abs(l[i]-l[i+1])*g) f*=-1 g*=-1 print(max(maxSubArraySum(x,n-1),maxSubArraySum(y,n-1))) # 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() main() #dmain() # Comment Read()
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.Scanner; /** * * @author Hodaifa A Quraini */ public class JavaApplication76 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } int arr1[] = new int[n - 1]; for (int i = 0; i < n - 1; i++) { arr1[i] = Math.abs(arr[i] - arr[i + 1]); } long max = Integer.MIN_VALUE; long result = 0; for (int i = 0; i < n - 1; i++) { if (i % 2 == 0) { result += arr1[i]; } else { result -= arr1[i]; } max = Math.max(result, max); if (result < 0) { result = 0; } } result=0; for (int i = 1; i < n - 1; i++) { if (i % 2 == 1) { result += arr1[i]; } else { result -= arr1[i]; } max = Math.max(result, max); if (result < 0) { result = 0; } } 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
def m(q): s=0 an=0 for i in range(len(q)): s+=q[i] if s<0: s-=q[i] an=max(s,an) s=0 an=max(s,an) an = max(s,an) return an n= int(input()) a=[int(x) for x in input().split()] z=[] y=[] p=-1 for i in range(0,n-1): p*=-1 z.append(p*abs(a[i]-a[i+1])) if i!=0: y.append((-1)*p*abs(a[i]-a[i+1])) print(max(m(z),m(y)))
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; import java.io.*; import java.math.*; public class Fuck{ static long MOD=(long)Math.pow(10,9)+7; static final int lint=Integer.MAX_VALUE; static final double ldouble=Double.MAX_VALUE; public static void main(String args[]) { new Thread(null, new Runnable() { public void run() { try{ solve(); } catch(Exception e){ e.printStackTrace(); } } }, "1", 1 << 26).start(); } static InputReader in; static PrintWriter w; static void solve(){ in = new InputReader(System.in); w = new PrintWriter(System.out); int n=in.nextInt(); long arr[]=new long[n]; for(int i=0;i<n;i++){ arr[i]=in.nextLong(); } long a1[]=new long[n-1]; long a2[]=new long[n-1]; for(int i=0;i<n-1;i++){ a1[i]=Math.abs(arr[i]-arr[i+1]); if(i%2==0){ a2[i]=-a1[i]; }else{ a2[i]=a1[i]; a1[i]=-a1[i]; } } long max=Long.MIN_VALUE; long maxsofar=0L; for(int i=0;i<a1.length;i++){ maxsofar=maxsofar+a1[i]; if(maxsofar>max){ max=maxsofar; } if(maxsofar<0){ maxsofar=0; if((i+1)%2==1){ i++; } } } maxsofar=0L; for(int i=1;i<a2.length;i++){ maxsofar=maxsofar+a2[i]; if(maxsofar>max){ max=maxsofar; } if(maxsofar<0){ maxsofar=0; if((i+1)%2==0){ i++; } } } w.println(max); w.close(); } // //if str2 (pattern) is subsequence of str1 (Text) or not // static boolean function(String str1,String str2){ // str2 = str2.replace("", ".*"); //returns .*a.*n.*n.*a. // return (str1.matches(str2)); // returns true // } static double convert(double a){ return Math.round(a * 100.0) / 100.0; } static boolean flag=false; static HashSet<Integer> ans; static int Arr[]; static long size[]; //modified initialize function: static void initialize(int N){ Arr=new int[N]; size=new long[N]; for(int i = 0;i<N;i++){ Arr[ i ] = i ; size[ i ] = 1; } } static boolean find(int A,int B){ if( root(A)==root(B) ) //if A and B have same root,means they are connected. return true; else return false; } // modified root function. static void weighted_union(int A,int B,int n){ int root_A = root(A); int root_B = root(B); if(size[root_A] < size[root_B ]){ Arr[ root_A ] = Arr[root_B]; size[root_B] += size[root_A]; } else{ Arr[ root_B ] = Arr[root_A]; size[root_A] += size[root_B]; } } static int root (int i){ while(Arr[ i ] != i){ Arr[ i ] = Arr[ Arr[ i ] ] ; i = Arr[ i ]; } return i; } // static long gcd(long a,long b){ // if(a==0){ // return b; // } // return gcd(b%a,a); // } // static boolean isPrime[]; //// //for marking all prime numbers greater than 1 and less than equal to N // static void sieve(int N) { // isPrime=new boolean[N+1]; // isPrime[0] = true; // isPrime[1] = true; // for(int i = 2; i * i <= N; ++i) { // if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers // for(int j = i * i; j <= N ;j += i) // isPrime[j] = true; // } // } // } // static boolean isPrime(long n) { // if(n < 2L) return false; // if(n == 2L || n == 3L) return true; // if(n%2L == 0 || n%3L == 0) return false; // long sqrtN = (long)Math.sqrt(n)+1L; // for(long i = 6L; i <= sqrtN; i += 6L) { // if(n%(i-1) == 0 || n%(i+1) == 0) return false; // } // return true; // } // static HashMap<Integer,Integer> level;; // static HashMap<Integer,Integer> parent; static int maxlevel=0; static ArrayList<Integer> adj[]; //Adjacency Lists static int V; // No. of vertices // Constructor static void Graph(int v){ V = v; adj = new ArrayList[v]; for (int i=0; i<v; ++i){ adj[i] = new ArrayList(); } } // Function to add an edge into the graph static void addEdge(int v,int w){ adj[v].add(w); // adj[w].add(v); } static void bfs(int s,int n){ boolean visited[]=new boolean[n]; LinkedList<Integer> queue=new LinkedList<Integer>(); queue.add(s); visited[s]=true; ans.add(s); while(!queue.isEmpty()){ int num=queue.pop(); // System.out.println(ans.toString()); if(flag){ break; } for(int i=0;i<adj[num].size();i++){ if(!visited[adj[num].get(i)]){ visited[adj[num].get(i)]=true; queue.add(adj[num].get(i)); ans.add(adj[num].get(i)); if(ans.size()==n){ flag=true; break; } } } } } // static boolean T[][][]; // static void subsetSum(int input[], int total, int count) { // T = new boolean[input.length + 1][total + 1][count+1]; // for (int i = 0; i <= input.length; i++) { // T[i][0][0] = true; // for(int j = 1; j<=count; j++){ // T[i][0][j] = false; // } // } // int sum[]=new int[input.length+1]; // for(int i=1;i<=input.length;i++){ // sum[i]=sum[i-1]+input[i-1]; // } // for (int i = 1; i <= input.length; i++) { // for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) { // for (int k = 1; k <= (int)Math.min(i,count); k++){ // if (j >= input[i - 1]) {//Exclude and Include // T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1]; // } else { // T[i][j][k] = T[i-1][j][k]; // } // } // } // } // } // static <K,V extends Comparable<? super V>> // SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) { // SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>( // new Comparator<Map.Entry<K,V>>() { // @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) { // int res = e2.getValue().compareTo(e1.getValue()); // return res != 0 ? res : 1; // } // } // ); // sortedEntries.addAll(map.entrySet()); // return sortedEntries; // } //minimum prime factor of all the numbers less than n static int minPrime[]; static void minimumPrime(int n){ minPrime=new int[n+1]; minPrime[1]=1; for (int i = 2; i * i <= n; ++i) { if (minPrime[i] == 0) { //If i is prime for (int j = i * i; j <= n; j += i) { if (minPrime[j] == 0) { minPrime[j] = i; } } } } for (int i = 2; i <= n; ++i) { if (minPrime[i] == 0) { minPrime[i] = i; } } } static long power(long base, long exponent, long modulus){ long result = 1; while (exponent > 0) { if (exponent % 2 == 1) result = (result * base) % modulus; exponent = exponent >> 1; base = (base * base) % modulus; } return result; } static long modInverse(long A, long M) { long x=extendedEuclid(A,M)[0]; return (x%M+M)%M; //x may be negative } static long[] extendedEuclid(long A, long B) { if(B == 0) { long d = A; long x = 1; long y = 0; return new long[]{x,y,d}; } else { long arr[]=extendedEuclid(B, A%B); long temp = arr[0]; arr[0] = arr[1]; arr[1] = temp - (A/B)*arr[1]; return arr; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } 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); } } } class NodeS{ char x; char y; public void setx(char x){ this.x=x; } public void sety(char y){ this.y=y; } public char getx(){ return x; } public char gety(){ return y; } }
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 long long MOD = 1000000007; const long long LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const int N = 1e5 + 5; long long a[N], b[N], c[N], d[N]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 1; i < n; i++) { d[i] = abs(a[i + 1] - a[i]); b[i] = c[i] = d[i]; } for (int i = 1; i < n; i += 2) b[i] *= -1; for (int i = 2; i < n; i += 2) c[i] *= -1; long long mn = 0, now = 0; long long res1 = 0, res2 = 0; for (int i = 1; i < n; i++) { now += b[i]; mn = min(mn, now); res1 = max(res1, now - mn); } now = mn = 0; for (int i = 1; i < n; i++) { now += c[i]; mn = min(mn, now); res2 = max(res2, now - mn); } printf("%lld\n", max(res1, res2)); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int N = 100005; int a[N], b[N]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", 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) b[i] = -b[i]; } long long ans = b[1], now = 0; for (int i = 1; i < n; ++i) { now += b[i]; ans = max(ans, now); if (now < 0) now = 0; } for (int i = 1; i < n; ++i) b[i] = -b[i]; now = 0; for (int i = 1; i < n; ++i) { now += b[i]; ans = max(ans, now); if (now < 0) now = 0; } cout << ans << endl; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int* arr = new int[n]; for (int i = 0; i < n; i++) cin >> arr[i]; int* dp1 = new int[n]; for (int i = 1; i < n; i++) dp1[i] = abs(arr[i - 1] - arr[i]); long long* dp2 = new long long[n]; dp2[0] = 0; for (int i = 1; i < n; i++) { if (i % 2 == 1) dp2[i] = dp2[i - 1] + dp1[i]; else dp2[i] = dp2[i - 1] - dp1[i]; } long long min = 0, max = -1; for (int i = 1; i < n; i++) { if (min > dp2[i]) min = dp2[i]; if (max < dp2[i]) max = dp2[i]; } cout << abs(max - min); 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 sys if __name__=='__main__': n = int(sys.stdin.readline()) A = [int(x) for x in sys.stdin.readline().split()] B = [ abs( A[i]-A[i+1] ) for i in range(n-1) ] C, m = [B[0]], -1 for i in range(1, n-1): C.append(C[i-1] + m*B[i]) m*=-1 #print(C) print( max( max(C), max(C)-min(C) ) )
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[100001]; long long S1[100001]; long long S1_suff_max[100001]; long long S2[100001]; long long S2_suff_max[100001]; int main() { ios::sync_with_stdio(false); cin.tie(0); int N; cin >> N; for (int i = 1; i <= N; i++) cin >> A[i]; for (int i = 2; i <= N; i++) { S1[i] = S1[i - 1]; if (i % 2 == 0) { S1[i] += abs(A[i] - A[i - 1]); } else { S1[i] -= abs(A[i] - A[i - 1]); } } S1_suff_max[N] = S1[N]; for (int i = N - 1; i >= 1; i--) { S1_suff_max[i] = max(S1[i], S1_suff_max[i + 1]); } for (int i = 2; i <= N; i++) { S2[i] = S2[i - 1]; if (i % 2 == 0) { S2[i] -= abs(A[i] - A[i - 1]); } else { S2[i] += abs(A[i] - A[i - 1]); } } S2_suff_max[N] = S2[N]; for (int i = N - 1; i >= 1; i--) { S2_suff_max[i] = max(S2[i], S2_suff_max[i + 1]); } long long ans = LLONG_MIN / 2; for (int i = 1; i < N; i += 2) { ans = max(ans, S1_suff_max[i + 1] - S1[i]); } for (int i = 2; i < N; i += 2) { ans = max(ans, S2_suff_max[i + 1] - S2[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
n=input() lst=map(int,raw_input().split()) 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 lst2=[] for i in range(0,n-1): vr=abs(lst[i+1]-lst[i])*(pow(-1,i)) lst2.append(vr) a =lst2 z=-10 #print"Maximum contiguous sum is" , maxSubArraySum(a,len(a)) for l in range(0,min(10,n-1)): k2=a[l:n] #print k2 for p in range(0,len(k2)): k2[p]=k2[p]*pow(-1,l) if(z<maxSubArraySum(k2,len(k2))): z=maxSubArraySum(k2,len(k2)) #print z print z
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Reader in = new Reader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Reader in, PrintWriter out) { int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } long lmax = Math.abs(arr[0] - arr[1]); int sign = -1; long rmax = sign * lmax; long l_max_so_far = lmax; long r_max_so_far = -lmax; for (int i = 1; i < n - 1; i++) { lmax = Math.max(Math.abs(arr[i] - arr[i + 1]) * sign, lmax + (Math.abs(arr[i] - arr[i + 1])) * sign); l_max_so_far = Math.max(l_max_so_far, lmax); rmax = Math.max(Math.abs(arr[i] - arr[i + 1]) * sign * -1, rmax + Math.abs(arr[i] - arr[i + 1]) * sign * -1); r_max_so_far = Math.max(rmax, r_max_so_far); sign *= -1; } // System.out.println(l_max_so_far+" "+r_max_so_far); long y = Math.max(l_max_so_far, r_max_so_far); String x = y + ""; out.write(x); } } static class Reader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private Reader.SpaceCharFilter filter; public Reader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
JAVA
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 = list(map(lambda i: abs(a[i] - a[i + 1]), range(n - 1))) x = list(map(lambda i: d[i] * (-1) ** i, range(0, n - 1))) y = list(map(lambda i: d[i] * (-1) ** (i + 1), range(0, n - 1))) max1 = x[0] s = 0 for l in range(0, n - 1, 1): s += x[l] max1 = max([max1, s]) s = max([s, 0]) max2 = max1 s = 0 for l in range(1, n - 1, 1): s += y[l] max2 = max([max2, s]) s = max([s, 0]) print(max2)
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.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] ar = new int[n]; for(int i = 0; i < n; i++) { ar[i] = sc.nextInt(); } sc.close(); int[] pslre = new int[n-1]; int[] ptlanlre = new int[n-1]; for(int i = 0; i < n-1; i++) { if(i % 2 == 0) { pslre[i] = Math.abs(ar[i]-ar[i+1]); ptlanlre[i] = Math.abs((ar[i]-ar[i+1]))*(-1); } else { ptlanlre[i] = Math.abs(ar[i]-ar[i+1]); pslre[i] = Math.abs((ar[i]-ar[i+1]))*(-1); } } long max = 0; long[] psjobbpotencial = new long[n]; long[] ptlanjobbpotencial = new long[n]; for(int i = n-3; i >= 0; i--) { psjobbpotencial[i] = Math.max((psjobbpotencial[i+1] + pslre[i+1]),0); } for(int i = n-3; i >= 0; i--) { ptlanjobbpotencial[i] = Math.max((ptlanjobbpotencial[i+1] + ptlanlre[i+1]),0); } for(int i = 0; i < n-1; i++) { if(i%2 == 0) { long ertek = psjobbpotencial[i] + pslre[i]; if(ertek > max) { max = ertek; } } else { long ertek = ptlanjobbpotencial[i] + ptlanlre[i]; if(ertek > max) { max = ertek; } } } 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 math input() seq = [0] + [ int(i) for i in input().split() ] cum = [0] + [ abs(seq[i - 1] - seq[i]) if i > 1 else 0 for i in range(1, len(seq)) ] mx = -math.inf eve = [0] * len(cum) odd = [0] * len(cum) for i in range(2, len(cum)): eve[i] = max( cum[i], odd[i - 1] + cum[i]) odd[i] = max(-cum[i], eve[i - 1] - cum[i]) mx = max(mx, odd[i], eve[i]) print(mx)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; void solve() { long long n; cin >> n; long long a[n]; for (long long i = 0; i < n; i++) cin >> a[i]; long long d[n - 1]; for (long long i = 1; i < n; i++) { d[i - 1] = abs(a[i] - a[i - 1]); } long long sum = 0, ans = LONG_MIN; for (long long i = 0; i < n - 1; i++) { if (i % 2) sum -= d[i]; else sum += d[i]; ans = max(sum, ans); if (sum < 0) sum = 0; } sum = 0; for (long long i = 0; i < n - 1; i++) { if (i % 2) sum += d[i]; else sum -= d[i]; ans = max(sum, ans); if (sum < 0) sum = 0; } cout << ans << "\n"; return; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long t = 1; while (t--) solve(); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> volatile bool isLocalTestEnabled = 0; bool g_isLocalPrintEnabled = (bool)(0); template <typename T> void UpdateMin(T& a, const T b) { a = std::min(a, b); } template <typename T> void UpdateMax(T& a, const T b) { a = std::max(a, b); } const long double Pi = std::atan(1.0L) * 4.0L; static const long double Eps = 1.0e-09; template <typename T> bool IsEqual(const T a, const T b) { return std::abs(a - b) < Eps; } template <typename T> bool IsGreater(const T a, const T b) { return a > b + Eps; } template <typename T> bool IsLess(const T a, const T b) { return a + Eps < b; } template <typename T> bool IsGreaterEqual(const T a, const T b) { return !IsLess(a, b); } template <typename T> bool IsLessEqual(const T a, const T b) { return !IsGreater(a, b); } template <typename T> std::string ToStr(const T& val) { std::ostringstream ostr; ostr << val; return ostr.str(); } template <typename T> bool FromStr(const std::string& str, T& val) { std::istringstream istr(str); istr >> val; return !!istr; } template <typename T> std::istream& operator>>(std::istream& ist, std::vector<T>& data) { ; for (size_t i = 0; i < data.size(); i++) { ist >> data[i]; } return ist; } template <typename T> T Read(std::istream& ist) { ; T val; ist >> val; return val; } template <typename T> std::ostream& operator<<(std::ostream& ost, const std::vector<T>& data) { for (size_t i = 0; i < data.size(); i++) { if (i != 0) { ost << ' '; } ost << data[i]; } return ost; } template <size_t id> class StopWatch {}; int64_t GetAns(const std::vector<int64_t>& a, size_t start) { if (a.size() < 2) return std::numeric_limits<int64_t>::min(); int64_t maxAns = std::abs(a[1] - a[0]); int64_t s = 0; int64_t m = 1; for (size_t i = start; i + 1 < a.size(); i++) { s += std::abs(a[i] - a[i + 1]) * m; m = -m; if (s > 0) { UpdateMax(maxAns, s); } else { s = 0; } } return maxAns; } bool Solve(std::istream& ist, std::ostream& ost, const bool multipleTestMode) { StopWatch<1> sw; (void)sw; size_t n; ist >> n; if (multipleTestMode && !ist) return false; std::vector<int64_t> a(n); ist >> a; if (!g_isLocalPrintEnabled) { } else std::cerr << std::endl << "Next test" << std::endl; const int64_t ans0 = GetAns(a, 0); const int64_t ans1 = GetAns(a, 1); const int64_t ans = std::max(ans0, ans1); ost << ans << std::endl; return multipleTestMode; } void RunSolve(std::istream& ist, std::ostream& ost) { Solve(ist, ost, false); } int main(int argc, const char* argv[]) { std::ios_base::sync_with_stdio(false); if (argc > 1) { std::ifstream ifs(argv[1]); if (!ifs) { std::cout << "File not found: " << argv[1] << std::endl; return 1; } RunSolve(ifs, std::cout); return 0; } RunSolve(std::cin, std::cout); }
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 A { static boolean tests = false; static void solve(){ int n = fs.nextInt(); long[] a = fs.readLongArray(n); long[] diff = new long[n]; for (int i = 0; i+1 < n; ++i){ diff[i] = Math.abs(a[i]-a[i+1]); } long[] dp = new long[n+1]; long ans = Math.max(diff[0], diff[1]); dp[0] = diff[0]; dp[1] = diff[1]; for (int i = 2; i < n; ++i){ dp[i] = diff[i]+Math.max(dp[i-2]-diff[i-1], 0); ans = Math.max(ans, dp[i]); } out.println(ans); } static FastScanner fs; static PrintWriter out; static int int_max = (int)1e9, mod = int_max+7; public static void main(String[] args) { fs = new FastScanner(); out = new PrintWriter(System.out); int t = 1; if (tests) t = fs.nextInt(); while (t-- > 0) solve(); out.close(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readLongArray(int n){ long a[] = new long[n]; for (int i = 0; i < n; ++i){ a[i] = nextLong(); } return a; } long nextLong() { return Long.parseLong(next()); } 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
import math n = int(input()) seq = [0] + list(map(int, input().split())) cum = [0] + list(abs(seq[i-1] - seq[i]) if i > 1 else 0 for i in range(1, n+1)) mx = -math.inf eve = [0]*len(cum) odd = [0]*len(cum) for i in range(2, len(cum)): eve[i] = max(cum[i], odd[i-1] + cum[i]) odd[i] = max(-cum[i], eve[i-1] - cum[i]) mx = max(mx, odd[i], eve[i]) print(mx)
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.Arrays; import java.util.Scanner; public class Prob3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long[] a = new long[n-1]; long last = in.nextLong(); for (int i = 1; i < n; i++) { long current = in.nextLong(); a[i-1] = Math.abs(last - current); last = current; } long max = 0; long sum = 0; for (int i = 0; i < n-1; i++) { if (sum < 0) sum = 0; if (i%2 == 0) sum += a[i]; else sum -= a[i]; if (sum > max) max = sum; } sum = 0; for (int i = 0; i < n-1; i++) { if (sum < 0) sum = 0; if (i%2 == 1) sum += a[i]; else sum -= a[i]; if (sum > max) max = sum; } System.out.println(max); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
# coding=utf-8 import sys import math import random # sys.stdin = open("a.in", "r") def __main__(): n = int(input()) d = [int(e) for e in input().split()] f = [abs(d[i+1] - d[i]) for i in range(n-1)] a = f[0] b = 0 ans = a for i in range(1, len(f)): if (i % 2 == 1): a = a - f[i] b = max(b + f[i], f[i]) ans = max(ans, a, b) else: a = max(a + f[i], f[i]) b = b - f[i] ans = max(ans, a, b) print(ans) 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())) b = [] for i in range(1, n): b.append(abs(a[i] - a[i-1])) n = len(b) for i in range(n): b[i] *= (-1) ** (i % 2) ans = 0 mx = 0 mi = 0 s = 0 for i in range(n): s += b[i] ans = max(ans, max(abs(s-mx), abs(s-mi))) mx = max(s, mx) mi = min(s, mi) print(ans)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int main() { long long int m1, m2, s, n, arr[100003], brr[100003]; scanf("%lld", &n); for (int i = 0; i < n; ++i) scanf("%lld", &arr[i]); for (int i = 0; i < n - 1; ++i) { brr[i] = abs(arr[i] - arr[i + 1]); if (i % 2) brr[i] *= -1; } m1 = -1000000000; s = 0; for (int i = 0; i < n - 1; ++i) { s += brr[i]; if (s < 0) s = 0; m1 = max(m1, s); } m2 = -1000000000; s = 0; for (int i = 0; i < n - 1; ++i) brr[i] *= -1; for (int i = 0; i < n - 1; ++i) { s += brr[i]; if (s < 0) s = 0; m2 = max(m2, s); } printf("%lld\n", 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
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Code { public static void main(String[] args) { // Use the Scanner class Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] A = new int[n]; for (int i = 0; i < n; ++i) { A[i] = sc.nextInt(); } System.out.println(f(A, n)); } static long f(int[] A, int n) { long[] d = new long[n-1]; int sgn = 1; for (int i = 0; i < n - 1; ++i) { d[i] = Math.abs(A[i+1] - A[i]); d[i] *= sgn; sgn = sgn*-1; } long result = max_sub_array_sum(d, 0); sgn = -1; for (int i = 0; i < n - 1; ++i) { d[i] *= sgn; } result = Math.max(result, max_sub_array_sum(d, 1)); return result; } static long max_sub_array_sum(long[] A, int start) { //print_array(A); if (A.length == start) { return Long.MIN_VALUE; } long max_so_far = A[start], max_end_here = A[start]; for (int i = start + 1; i < A.length; ++i) { max_end_here = Math.max(max_end_here + A[i], A[i]); max_so_far = Math.max(max_so_far, max_end_here); } return max_so_far; } static void print_array(long[] A) { for (long l : A) { System.out.print(String.format("%d ", l)); } System.out.println(); } }
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
from sys import stdin n=int(stdin.readline()) a=list(map(int,stdin.readline().split())) if n==2: print(abs(a[0]-a[1])) exit() mx_cur1,mx_glob1=abs(a[0]-a[1]),abs(a[0]-a[1]) for i in range(1,n-1): tmp=abs(a[i]-a[i+1])*(-1)**i mx_cur1=max(mx_cur1+tmp,tmp) mx_glob1=max(mx_cur1,mx_glob1) mx_cur2,mx_glob2=abs(a[1]-a[2]),abs(a[1]-a[2]) for i in range(2,n-1): tmp=abs(a[i]-a[i+1])*(-1)**(i-1) mx_cur2=max(mx_cur2+tmp,tmp) mx_glob2=max(mx_glob2,mx_cur2) print(max(mx_glob1,mx_glob2))
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; public class Codeforces { private static void sport(int[] a) { int n = a.length; int[] b = new int[n-1]; for (int i = 0; i < n-1; i++) { b[i]=Math.abs(a[i]-a[i+1]); } //-3 2 -1 2 System.out.println(Math.max(max(b,0),max(b,1))); } static long max(int[] a, int j){ long ans=0; long res=0; boolean pos=true; for (int i = j; i < a.length; i++) { if (pos){ res+=a[i]; pos=!pos; }else{ res-=a[i]; pos=!pos; } if (res<0){ res=0; } ans=Math.max(ans,res); } return ans; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i]=sc.nextInt(); } sport(a); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); AFunctionsAgain solver = new AFunctionsAgain(); solver.solve(1, in, out); out.close(); } } static class AFunctionsAgain { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] a = new int[n]; in.populate(a); ArrayIndex ai = new ArrayIndex(n, 2); long[] dp = new long[ai.totalSize()]; for (int i = n - 2; i >= 0; i--) { long contrib = Math.abs(a[i] - a[i + 1]); dp[ai.indexOf(i, 0)] = Math.min(dp[ai.indexOf(i, 0)], contrib - dp[ai.indexOf(i + 1, 1)]); dp[ai.indexOf(i, 1)] = Math.max(dp[ai.indexOf(i, 1)], contrib - dp[ai.indexOf(i + 1, 0)]); } long ans = 0; for (int i = 0; i < n; i++) { ans = Math.max(ans, dp[ai.indexOf(i, 1)]); } out.println(ans); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(long c) { cache.append(c); return this; } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } public void populate(int[] data) { for (int i = 0; i < data.length; i++) { data[i] = readInt(); } } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class ArrayIndex { int[] dimensions; public ArrayIndex(int... dimensions) { this.dimensions = dimensions; } public int totalSize() { int ans = 1; for (int x : dimensions) { ans *= x; } return ans; } public int indexOf(int a, int b) { return a * dimensions[1] + b; } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int a[100005]; int b[100005], n; int main() { cin >> n; for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i < n; i++) b[i] = abs(a[i] - a[i + 1]); long long s = b[1], s1 = b[1]; int l = 1; for (int i = 2; i < n; i++) { while (s <= 0 && i - l > 1) s -= b[l] - b[l + 1], l += 2; s += b[i] * (i % 2 ? 1 : -1); s1 = max(s1, s); } while (l < n - 1) s -= b[l] - b[l + 1], l += 2, s1 = max(s1, s); s1 = max(s = b[2], s1); l = 2; for (int i = 3; i < n; i++) { while (s <= 0 && i - l > 1) s -= b[l] - b[l + 1], l += 2; s += b[i] * (i % 2 ? -1 : 1); s1 = max(s1, s); } while (l < n - 1) s -= b[l] - b[l + 1], l += 2, s1 = max(s1, s); cout << s1; 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())) b=[abs(a[i]-a[i+1]) for i in range(n-1)] for i in range(0,n-1,2): b[i]*=-1 dp=[0]*(n-1) dp[0]=b[0] for i in range(1,n-1): dp[i]=max(dp[i-1]+b[i],b[i]) ans=max(dp) for i in range(n-1): b[i]*=-1 dp=[0]*(n-1) dp[0]=b[0] for i in range(1,n-1): dp[i]=max(dp[i-1]+b[i],b[i]) ans=max(ans,max(dp)) print(ans)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = in.nextInt(); int[]a= new int[n]; for (int i =0;i<n;i++) a[i]=in.nextInt(); long max=0; long ans=0; for (int i =0;i<n-1;i++) { if (ans<0) { ans=0; } if (i%2==0) { ans+=Math.abs(a[i]-a[i+1]); } else ans-=(Math.abs(a[i]-a[i+1])); max=Math.max(max,ans); } ans=0; for (int i =0;i<n-1;i++) { if (ans<0) { ans=0; } if (i%2==1) { ans+=Math.abs(a[i]-a[i+1]); } else ans-=(Math.abs(a[i]-a[i+1])); max=Math.max(max,ans); } out.printLine(max); out.flush(); } } class pair implements Comparable { int key; int value; public pair(Object key, Object value) { this.key = (int)key; this.value=(int)value; } @Override public int compareTo(Object o) { pair temp =(pair)o; return key-temp.key; } } class Graph { int n; ArrayList<Integer>[] adjList; public Graph(int n) { this.n = n; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } 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; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≀ l < r ≀ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≀ ai ≀ 109) β€” the array elements. Output Print the only integer β€” the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; import java.io.*; public class Functions_Again { 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; } } public static void shuffle(int[] a) { Random r = new Random(); for (int i = 0; i <= a.length - 2; i++) { int j = i + r.nextInt(a.length - i); swap(a, i, j); } Arrays.sort(a); } public static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int n = t.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; ++i) a[i] = t.nextLong(); long[] dif = new long[n - 1]; for (int i = 1; i < n; ++i) dif[i - 1] = Math.abs(a[i] - a[i - 1]) * ((i & 1) == 1 ? +1 : -1); long max1 = kadane(0, dif); for (int i = 0; i < n - 1; ++i) dif[i] = -dif[i]; long max2 = kadane(1, dif); o.println(Math.max(max1, max2)); o.flush(); o.close(); } private static long kadane(int i, long[] dif) { int n = dif.length; long maxSum = Integer.MIN_VALUE; long curSum = 0; while (i < n) { curSum += dif[i]; maxSum = Math.max(maxSum, curSum); if (curSum < 0) curSum = 0; ++i; } return 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
#include <bits/stdc++.h> using namespace std; long long A[100005], f[100005], d[100005]; int main() { long long n; cin >> n; f[0] = 0; for (long long i = 0; i < n; i++) { cin >> A[i]; if (i) { d[i - 1] = abs(A[i] - A[i - 1]); if (i % 2) f[i] = f[i - 1] + d[i - 1]; else f[i] = f[i - 1] - d[i - 1]; } } sort(f, f + n); cout << f[n - 1] - f[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
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { long best(int n, int[] a) { long re = Long.MIN_VALUE; long sum = 0; for (int i = 0; i < n; ++i) { if (sum < 0) sum = 0; sum += a[i]; re = Math.max(sum, re); } return re; } public void solve(int testNumber, InputReader in, PrintWriter out) { long startTime = System.currentTimeMillis(); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); n--; for (int i = 0; i < n; ++i) a[i] = Math.abs(a[i] - a[i + 1]); for (int i = 0; i < n; ++i) if (i % 2 == 0) { a[i] = -a[i]; } long re = best(n, a); for (int i = 0; i < n; ++i) a[i] = -a[i]; re = Math.max(re, best(n, a)); out.println(re); System.err.println("Time: " + (System.currentTimeMillis() - startTime) + " miliseconds"); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || 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
n=int(input()) a=input().split() arr=[abs(int(a[i])-int(a[i+1]))*(-1)**i for i in range(n-1)] maximum=0 summ=0 for j in arr: if j>0 or abs(j)<abs(summ): summ+=j else: summ=0 maximum=max(maximum, abs(summ)) summ=0 for k in arr[1:]: if k<0 or abs(k)<abs(summ): summ+=k else: summ=0 maximum=max(maximum, abs(summ)) print(maximum)
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 n, ans, ans2, sum, a[500000], d1[500000], d2[500000]; int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i < n; i++) { d1[i + 1] = abs(a[i] - a[i + 1]); if (i % 2 == 0) d1[i + 1] *= -1ll; d2[i + 1] = abs(a[i] - a[i + 1]); if (i % 2 == 1) d2[i + 1] *= -1ll; } ans = d1[2]; sum = 0ll; for (int i = 2; i <= n; ++i) { sum += d1[i]; ans = max(ans, sum); sum = max(sum, 0ll); } ans2 = d2[2]; sum = 0ll; for (int i = 2; i <= n; ++i) { sum += d2[i]; ans2 = max(ans2, sum); sum = max(sum, 0ll); } cout << max(max(ans, ans2), 0ll) << 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; long long int a[100005], dp[100005][2], dpsol[100005]; void init() { memset(dp, -1, sizeof(dp)); memset(dpsol, -1, sizeof(dpsol)); return; } void maxm(long long int st, long long int en) { for (long long int i = en; i >= st; i--) { if (i == en) { dp[i][0] = dp[i][1] = 0; } else if (i == en - 1) { dp[i][0] = dp[i][1] = abs(a[i] - a[i + 1]); } else { long long int tmp = abs(a[i] - a[i + 1]); dp[i][0] = max(tmp, max(tmp - dp[i + 1][0], tmp - dp[i + 1][1])); dp[i][1] = min(tmp, min(tmp - dp[i + 1][0], tmp - dp[i + 1][1])); } } return; } void sol(long long int st, long long int en) { for (long long int i = en; i >= st; i--) { if (i == en) { dpsol[i] = 0; } else if (i == en - 1) { dpsol[i] = abs(a[i] - a[i + 1]); } else { dpsol[i] = max(dpsol[i + 1], max(dp[i][0], dp[i][1])); } } return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); init(); long long int n; cin >> n; for (long long int i = 0; i < n; i++) cin >> a[i]; maxm(0, n - 1); sol(0, n - 1); cout << dpsol[0] << 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 sun.misc.resources.Messages_pt_BR; import javax.print.attribute.standard.MediaPrintableArea; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; /** * Created by FirΠ΅fly on 1/1/2017. */ public class Task { public static void main(String[] args) throws IOException { Emaxx emaxx = new Emaxx(); } } class Emaxx { FScanner fs; PrintWriter pw; Emaxx() throws IOException { fs = new FScanner(new InputStreamReader(System.in)); // pw = new PrintWriter(new FileWriter("arithnumbers.out")); // fs = new FScanner(new FileReader("C:\\Users\\FirΠ΅fly\\Desktop\\New Text Document.txt")); // fs = new FScanner(new FileReader("input.txt"));; // pw = new PrintWriter("output.txt"); PrintWriter pw = new PrintWriter(System.out); int n = fs.nextInt(); int[] mas = new int[n]; for (int i = 0; i<n; i++) mas[i] = fs.nextInt(); long sumEven = 0; long sumOdd = (long) -1e18, curSumEv = 0, curSumOd = 0; for (int i =0; i<n-1; i++) { curSumEv+= i%2 ==0? Math.abs(mas[i]-mas[i+1]) : -Math.abs(mas[i]-mas[i+1]); sumEven = Math.max(sumEven, curSumEv); if (curSumEv<0) curSumEv = 0; } for (int i = 1; i<n-1; i++) { curSumOd+= i%2 == 0? -Math.abs(mas[i]-mas[i+1]) : Math.abs(mas[i]-mas[i+1]); sumOdd = Math.max(sumOdd, curSumOd); if (curSumOd<0) curSumOd = 0; } pw.println(Math.max(sumEven, sumOdd)); pw.close(); } int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a%b); } } class FScanner { BufferedReader br; StringTokenizer st; FScanner(InputStreamReader isr) { br = new BufferedReader(isr); } FScanner(FileReader fr) { br = new BufferedReader(fr); } String nextToken() throws IOException{ while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return br.readLine(); } char nextChar() throws IOException { return (char) br.read(); } }
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> #pragma GCC optimize("O3") using namespace std; inline long long getint() { long long _x = 0, _tmp = 1; char _tc = getchar(); while ((_tc < '0' || _tc > '9') && _tc != '-') _tc = getchar(); if (_tc == '-') _tc = getchar(), _tmp = -1; while (_tc >= '0' && _tc <= '9') _x *= 10, _x += (_tc - '0'), _tc = getchar(); return _x * _tmp; } inline long long add(long long _x, long long _y, long long _mod = 1000000007LL) { _x += _y; return _x >= _mod ? _x - _mod : _x; } inline long long sub(long long _x, long long _y, long long _mod = 1000000007LL) { _x -= _y; return _x < 0 ? _x + _mod : _x; } inline long long mul(long long _x, long long _y, long long _mod = 1000000007LL) { _x *= _y; return _x >= _mod ? _x % _mod : _x; } long long mypow(long long _a, long long _x, long long _mod) { if (_x == 0) return 1LL; long long _ret = mypow(mul(_a, _a, _mod), _x >> 1, _mod); if (_x & 1) _ret = mul(_ret, _a, _mod); return _ret; } long long mymul(long long _a, long long _x, long long _mod) { if (_x == 0) return 0LL; long long _ret = mymul(add(_a, _a, _mod), _x >> 1, _mod); if (_x & 1) _ret = add(_ret, _a, _mod); return _ret; } inline bool equal(double _x, double _y) { return _x > _y - 1e-9 && _x < _y + 1e-9; } int __ = 1, _cs; void build() {} long long n, a[101010], b[101010]; void init() { n = getint(); for (int i = 0; i < n; i++) a[i] = getint(); } void solve() { for (int i = 0; i + 1 < n; i++) b[i] = abs(a[i + 1] - a[i]); long long mx = 0, mn = 0, ans = 0, ps = 0; for (int i = n - 2, sign = 1; i >= 0; i--, sign = -sign) { ps += b[i] * sign; if (sign > 0) ans = max(ans, ps - mn); else ans = max(ans, -(ps - mx)); mx = max(mx, ps); mn = min(mn, ps); } printf("%lld\n", ans); } int main() { build(); while (__--) { init(); solve(); } }
CPP