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;
int main(int argc, const char* argv[]) {
std::ios::sync_with_stdio(false);
int n;
cin >> n;
vector<long long> data(n);
for (int i = 0; i < n; ++i) {
cin >> data[i];
}
vector<long long> data2;
for (int i = 0; i < n - 1; ++i) {
data2.push_back(abs(data[i] - data[i + 1]));
}
assert(data2.size() == n - 1);
long long res = 0;
long long curr = 0;
for (int i = 0; i < data2.size(); ++i) {
if (i % 2 == 0) {
curr += data2[i];
} else {
curr -= data2[i];
}
curr = max(curr, 0ll);
res = max(res, curr);
}
curr = 0;
for (int i = 1; i < data2.size(); ++i) {
if (i % 2 == 1) {
curr += data2[i];
} else {
curr -= data2[i];
}
curr = max(curr, 0ll);
res = max(res, curr);
}
cout << res << endl;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class D {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
static String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static int readInt() throws IOException {
return Integer.parseInt(readString());
}
static long readLong() throws IOException {
return Long.parseLong(readString());
}
private static void solve() throws IOException {
int n = readInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = readInt();
}
long[] deltas = new long[n - 1];
for (int i = 0; i < n - 1; i++) {
deltas[i] = Math.abs(a[i] - a[i + 1]);
if (i % 2 == 1) deltas[i] = -deltas[i];
}
long ans = 0;
long sum = 0;
for (int i = 0; i < n - 1; i++) {
sum = Math.max(sum + deltas[i], 0);
ans = Math.max(ans, sum);
}
for (int i = 0; i < n - 1; i++) {
deltas[i] = -deltas[i];
}
sum = 0;
for (int i = 1; i < n - 1; i++) {
sum = Math.max(sum + deltas[i], 0);
ans = Math.max(ans, sum);
}
out.print(ans);
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | //package fb1;
//package fb1;
import java.util.*;
import java.io.*;
import java.lang.Math.*;
public class MainA {
public static int mod = 20000;
public static long[] val;
public static long[] arr;
static long max = (long) 1e10 + 7;
static long count=0;
static int l=0;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=in.nextInt();
long a[]=new long[n];
for(int i=0;i<n;i++)
{
a[i]=in.nextLong();
}
long ans=0;
if(n==2)
{
ans=Math.abs(a[0]-a[1]);
}
else{
long b[]=new long[n];
for(int i=0;i<n-1;i++)
{
if(i%2==0)b[i]=Math.abs(a[i]-a[i+1]);
else b[i]=Math.abs(a[i]-a[i+1])*(-1);
}
ans=maxS(b,b.length);
long c[]=new long[n];
for(int i=1;i<n-1;i++)
{
if(i%2==1)c[i]=Math.abs(a[i]-a[i+1]);
else c[i]=Math.abs(a[i]-a[i+1])*(-1);
}
if(ans <maxS(c,c.length))ans=maxS(c,c.length);
}
System.out.println(ans);
out.close();
}
static long maxS(long a[], int size)
{
long max_so_far = 0, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;
/* Do not compare for all elements. Compare only
when max_ending_here > 0 */
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
static boolean count(int mid,int a[][],int n,int dp[][])
{
int f=1,temp=0;
for(int i=0;i<=n-mid;i++)
{
for(int j=0;j<=n-mid;j++)
{
f=1;
for(int k=i;k<mid;k++)
{
/*for(int l=j;l<mid;l++)
{
if(k==i && l==j)temp=a[k][l];
else if(temp!=a[k][l])
{
f=0;
break;
}
}
*/
if(dp[k][mid-1]!=j)
{
f=0;
break;
}
else
{
if(k==i)
temp=a[k][mid-1];
else if(temp!=a[k][mid-1])
{
f=0;
break;
}
}
}
if(f==1)
{
return true;
}
}
}
return false;
}
static class Pairs implements Comparable<Pairs> {
int x;
int y;
Pairs(int a, int b) {
x = a;
y = b;
}
@Override
public int compareTo(Pairs o) {
// TODO Auto-generated method stub
if (x == o.x)
return Integer.compare(y, o.y);
else
return Integer.compare(x, o.x);
}
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static boolean isPal(String s) {
for (int i = 0, j = s.length() - 1; i <= j; i++, j--) {
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
public static String rev(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x, long y) {
if (y == 0)
return x;
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static int gcd(int x, int y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static long gcdExtended(long a, long b, long[] x) {
if (a == 0) {
x[0] = 0;
x[1] = 1;
return b;
}
long[] y = new long[2];
long gcd = gcdExtended(b % a, a, y);
x[0] = y[1] - (b / a) * y[0];
x[1] = y[0];
return gcd;
}
public static int abs(int a, int b) {
return (int) Math.abs(a - b);
}
public static long abs(long a, long b) {
return (long) Math.abs(a - b);
}
public static int max(int a, int b) {
if (a > b)
return a;
else
return b;
}
public static int min(int a, int b) {
if (a > b)
return b;
else
return a;
}
public static long max(long a, long b) {
if (a > b)
return a;
else
return b;
}
public static long min(long a, long b) {
if (a > b)
return b;
else
return a;
}
public static long[][] mul(long a[][], long b[][]) {
long c[][] = new long[2][2];
c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0];
c[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1];
c[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0];
c[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1];
return c;
}
public static long[][] pow(long n[][], long p, long m) {
long result[][] = new long[2][2];
result[0][0] = 1;
result[0][1] = 0;
result[1][0] = 0;
result[1][1] = 1;
if (p == 0)
return result;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result = mul(result, n);
//System.out.println(result[0][0]);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (result[i][j] >= m)
result[i][j] %= m;
}
}
p >>= 1;
n = mul(n, n);
// System.out.println(1+" "+n[0][0]+" "+n[0][1]+" "+n[1][0]+" "+n[1][1]);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (n[i][j] >= m)
n[i][j] %= m;
}
}
}
return result;
}
public static long pow(long n, long p) {
long result = 1;
if (p == 0)
return 1;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result *= n;
p >>= 1;
n *= n;
}
return result;
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 | #include <bits/stdc++.h>
using std::vector;
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
size_t array_size;
std::cin >> array_size;
vector<int64_t> array(array_size);
for (auto& elem : array) {
std::cin >> elem;
}
vector<int64_t> diffs;
for (size_t i = 1; i < array.size(); ++i) {
diffs.push_back(llabs(array[i] - array[i - 1]));
}
vector<int64_t> prefix_sums{0};
for (auto elem : diffs) {
if (prefix_sums.size() % 2 == 0) {
prefix_sums.push_back(prefix_sums.back() - elem);
} else {
prefix_sums.push_back(prefix_sums.back() + elem);
}
}
vector<size_t> min_pos, max_pos;
for (size_t i = 0; i < prefix_sums.size(); ++i) {
while (!min_pos.empty() && prefix_sums[min_pos.back()] >= prefix_sums[i]) {
min_pos.pop_back();
}
while (!max_pos.empty() && prefix_sums[max_pos.back()] <= prefix_sums[i]) {
max_pos.pop_back();
}
min_pos.push_back(i);
max_pos.push_back(i);
}
int64_t best_way = 0;
size_t min_pos_pos = 0, max_pos_pos = 0;
for (size_t i = 0; i < prefix_sums.size(); ++i) {
if (i > min_pos[min_pos_pos]) {
++min_pos_pos;
}
if (i > max_pos[max_pos_pos]) {
++max_pos_pos;
}
if (i % 2) {
best_way = std::max(best_way, (-1) * (prefix_sums[min_pos[min_pos_pos]] -
prefix_sums[i]));
} else {
best_way = std::max(best_way,
prefix_sums[max_pos[max_pos_pos]] - prefix_sums[i]);
}
}
std::cout << best_way;
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 = 100010;
int main() {
int n;
long long a[maxn];
long long dp[maxn], cp[maxn];
while (cin >> n) {
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) a[i] = abs(a[i + 1] - a[i]);
long long ans = 0;
for (int i = n - 2; i >= 0; i--) {
dp[i] = max(a[i], a[i] - cp[i + 1]);
cp[i] = min(a[i], a[i] - dp[i + 1]);
ans = max(ans, dp[i]);
}
cout << ans << endl;
}
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long dp[100005], a[100005];
int main() {
ios::sync_with_stdio(false);
int n;
long long ans1 = 0, ans2 = 0, ans = 0, pre, now;
cin >> n;
cin >> pre;
for (int i = 1; i < n; i++) {
cin >> now;
a[i] = abs(now - pre);
pre = now;
}
for (int i = 1; i < n; i++) {
if (i & 1) {
ans1 = max(ans1, ans1 + a[i]);
ans2 = max(0ll, ans2 - a[i]);
} else {
ans2 = max(ans2, ans2 + a[i]);
ans1 = max(0ll, ans1 - a[i]);
}
ans = max(ans, max(ans1, ans2));
}
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 = int(raw_input())
a = [int(x) for x in raw_input().split()]
l = []
if n == 1:
print 0
exit()
if n == 2:
print abs(a[0]-a[1])
exit()
for i in range(len(a)-1):
l.append(abs(a[i]-a[i+1]))
ans = [-1]*len(l)
ans[-1] = l[-1]
ans[-2] = l[-2]
for i in range(-3,-n,-1):
ans[i] = max(l[i],l[i]+ans[i+2]-l[i+1])
print max(ans)
| PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.lang.*;
import java.math.*;
import java.text.DecimalFormat;
import java.lang.reflect.Array;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
public class Codeforces{
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static long MOD = (long)(1e9+7);
//static long MOD = 998244353;
static FastReader sc = new FastReader();
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
public static void main(String[] args){
int test = 1;
//test = sc.nextInt();
while(test-->0){
int n = sc.nextInt();
long[] a = new long[n];
for(int i = 0; i< n; i++) {
a[i] = sc.nextLong();
}
long[] f = new long[n-1];
for(int i = 1;i < n; i++) {
f[i-1] = Math.abs(a[i]-a[i-1]);
}
long[] dp = new long[n-1];
dp[0] = f[0];
if(n>2) {
dp[1] = f[1];
}
for(int i = 2; i < n-1; i++) {
dp[i] = Math.max(f[i], f[i]+dp[i-2]-f[i-1]);
}
long ans = Long.MIN_VALUE;
for(int i = 0; i< n-1; i++) {
ans = Math.max(ans, dp[i]);
}
out.println(ans);
//print1d(dp);
}
out.close();
}
public static long mul(long a, long b){
return ((a%MOD)*(b%MOD))%MOD;
}
public static long add(long a, long b){
return ((a%MOD)+(b%MOD))%MOD;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Integer.lowestOneBit(i) Equals k where k is the position of the first one in the binary
//Integer.highestOneBit(i) Equals k where k is the position of the last one in the binary
//Integer.bitCount(i) returns the number of one-bits
//Collections.sort(A,(p1,p2)->(int)(p2.x-p1.x)) To sort ArrayList in descending order wrt values of x.
// Arrays.parallelSort(a,new Comparator<TPair>() {
// public int compare(TPair a,TPair b) {
// if(a.y==b.y) return a.x-b.x;
// return b.y-a.y;
// }
// });
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PrimeFactors
public static ArrayList<Long> primeFactors(long n) {
ArrayList<Long> arr = new ArrayList<>();
if (n % 2 == 0)
arr.add((long) 2);
while (n % 2 == 0)
n /= 2;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
int flag = 0;
while (n % i == 0) {
n /= i;
flag = 1;
}
if (flag == 1)
arr.add(i);
}
if (n > 2)
arr.add(n);
return arr;
}
//Pair Class
static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if(this.x==o.x){
return (this.y-o.y);
}
return (this.x-o.x);
}
}
static class TPair implements Comparable<TPair>{
int two;
int three;
int prime;
public TPair(int two, int three, int prime) {
this.two = two;
this.three = three;
this.prime = prime;
}
@Override
public int compareTo(TPair o) {
if(this.three==o.three){
return (this.two-o.two);
}
return -1*(this.three-o.three);
}
}
//nCr
static long ncr(long n, long k) {
long ret = 1;
for (long x = n; x > n - k; x--) {
ret *= x;
ret /= (n - x + 1);
}
return ret;
}
static long finextDoubleMMI_fermat(long n,int M)
{
return fastExpo(n,M-2);
}
static long nCrModPFermat(int n, int r, int p)
{
if (r == 0)
return 1;
long[] fac = new long[n+1];
fac[0] = 1;
for (int i = 1 ;i <= n; i++)
fac[i] = fac[i-1] * i % p;
return (fac[n]* finextDoubleMMI_fermat(fac[r], p)% p * finextDoubleMMI_fermat(fac[n-r], p) % p) % p;
}
//Merge Sort
static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long [n1];
long R[] = new long [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
//Brian Kernighanβs Algorithm
static long countSetBits(long n){
if(n==0) return 0;
return 1+countSetBits(n&(n-1));
}
//Factorial
static long factorial(long n){
if(n==1) return 1;
if(n==2) return 2;
if(n==3) return 6;
return n*factorial(n-1);
}
//Euclidean Algorithm
static long gcd(long A,long B){
if(B==0) return A;
return gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//AKS Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i<=Math.sqrt(n);i+=6)
if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Reverse an array
static <T> void reverse(T arr[],int l,int r){
Collections.reverse(Arrays.asList(arr).subList(l, r));
}
//Print array
static void print1d(long arr[]) {
out.println(Arrays.toString(arr));
}
static void print2d(int arr[][]) {
for(int a[]: arr) out.println(Arrays.toString(a));
}
//Sieve of eratosthenes
static int[] findPrimes(int n){
boolean isPrime[]=new boolean[n+1];
ArrayList<Integer> a=new ArrayList<>();
int result[];
Arrays.fill(isPrime,true);
isPrime[0]=false;
isPrime[1]=false;
for(int i=2;i*i<=n;++i){
if(isPrime[i]==true){
for(int j=i*i;j<=n;j+=i) isPrime[j]=false;
}
}
for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i);
result=new int[a.size()];
for(int i=0;i<a.size();i++) result[i]=a.get(i);
return result;
}
//Indivisual factors of all nos till n
static ArrayList<Integer>[] indiFactors(int n){
ArrayList<Integer>[] A = new ArrayList[n+1];
for(int i = 0; i <= n; i++) {
A[i] = new ArrayList<>();
}
int[] sieve = new int[n+1];
for(int i=2;i<=n;i++) {
if(sieve[i]==0) {
for(int j=i;j<=n;j+=i) if(sieve[j]==0) {
//sieve[j]=i;
A[j].add(i);
}
}
}
return A;
}
//Segmented Sieve
static boolean[] segmentedSieve(long l, long r){
boolean[] segSieve = new boolean[(int)(r-l+1)];
Arrays.fill(segSieve, true);
int[] prePrimes = findPrimes((int)Math.sqrt(r));
for(int p:prePrimes) {
long low = (l/p)*p;
if(low < l) {
low += p;
}
if(low == p) {
low += p;
}
for(long j = low; j<= r; j += p) {
segSieve[(int) (j-l)] = false;
}
}
if(l==1) {
segSieve[0] = false;
}
return segSieve;
}
//Euler Totent function
static long countCoprimes(long n){
ArrayList<Long> prime_factors=new ArrayList<>();
long x=n,flag=0;
while(x%2==0){
if(flag==0) prime_factors.add(2L);
flag=1;
x/=2;
}
for(long i=3;i*i<=x;i+=2){
flag=0;
while(x%i==0){
if(flag==0) prime_factors.add(i);
flag=1;
x/=i;
}
}
if(x>2) prime_factors.add(x);
double ans=(double)n;
for(Long p:prime_factors){
ans*=(1.0-(Double)1.0/p);
}
return (long)ans;
}
static long modulo = (long)1e9+7;
public static long modinv(long x){
return modpow(x, modulo-2);
}
public static long modpow(long a, long b){
if(b==0){
return 1;
}
long x = modpow(a, b/2);
x = (x*x)%modulo;
if(b%2==1){
return (x*a)%modulo;
}
return x;
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is quite fast
//than using direct
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception r) {
r.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());//converts string to integer
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception r) {
r.printStackTrace();
}
return str;
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
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;
m = max(m, sum);
}
}
int main() {
cin >> n;
long long num, last;
cin >> last;
n--;
for (int i = 0; i < n; i++) {
cin >> 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();
cout << 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 | import java.util.*;
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
FastScanner qwe = new FastScanner(System.in);
int n = qwe.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = qwe.nextInt();
}
long best = 0;
for(int i =0; i< 2; i++){
int[] b = new int[n-1-i];
int mult = 1;
for(int j = i; j < a.length-1; j++){
b[j-i] = Math.abs(a[j+1]-a[j])*(mult);
mult *= -1;
}
best = Math.max(max(b), best);
}
System.out.println(best);
qwe.close();
}
static long max(int[] b){
if(b.length == 0) return 0;
//System.out.println(Arrays.toString(b));
long best = 0;
int l = 0;
int r = 1;
long running = (best =b[0]);
while(r < b.length){
running += b[r++];
while(running < 0 && l < r){
running -= b[l++];
}
best = Math.max(best, running);
}
return best;
}
static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException
{
while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
public void close() throws IOException
{
br.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 |
if __name__ == "__main__":
n = input()
a = map(int, raw_input().split())
f = [0] * (n - 1)
for i in range(n - 1):
f[i] = abs(a[i] - a[i + 1])
res = max(f)
tmp = 0
for i in range(n - 1):
fi = f[i]
if (i % 2 != 0):
fi = -fi
tmp += fi
if tmp <= 0:
tmp = 0
else:
if tmp > res:
res = tmp
tmp = 0
for i in range(1, n - 1):
fi = f[i]
if (i % 2 == 0):
fi = -fi
tmp += fi
if tmp <= 0:
tmp = 0
else:
if tmp > res:
res = tmp
print res
| PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 100004;
long long a[N], b[N];
int n, p = 0;
long long fun(int n) {
long long ans = 0, sum = 0;
for (int i = 1; i <= n; i++) {
sum += b[i];
if (sum < 0) sum = 0;
ans = max(ans, sum);
}
return ans;
}
int main() {
long long ans = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
for (int i = 1; i < n; i++)
a[i] = ((a[i + 1] - a[i]) > 0 ? (a[i + 1] - a[i]) : -(a[i + 1] - a[i]));
--n;
for (int i = 1; i <= n; i++) b[i] = i & 1 ? a[i] : -a[i];
ans = fun(n);
for (int i = 2; i <= n; i++) b[++p] = i & 1 ? -a[i] : a[i];
ans = max(ans, fun(p));
printf("%lld\n", ans);
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(input())
a = [*map(int, input().split())]
s = [abs(a[i] - a[i + 1]) for i in range(n - 1)]
x = y = ans = 0
for i in s:
x1 = max(y + i, 0)
y1 = max(x - i, 0)
x, y, ans = x1, y1, max(x1, y1, ans)
print(ans) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<long long> a(n);
for (auto &it : a) cin >> it;
;
long long dp[n + 5][5];
memset(dp, 0, sizeof(dp));
dp[0][1] = abs(a[0] - a[1]);
long long ans = dp[0][1];
for (int i = 1; i < n - 1; i++) {
dp[i][1] = max(dp[i - 1][0] + abs(a[i] - a[i + 1]), abs(a[i] - a[i + 1]));
dp[i][0] = dp[i - 1][1] - abs(a[i] - a[i + 1]);
ans = max({ans, dp[i][1], dp[i][0]});
}
cout << ans << '\n';
}
int main() { solve(); }
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | lectura= lambda:map (int, input().split())
n= (list(lectura())[0])
lista= list(lectura())
fDescrita=0
alt1=1
maxV1=0
maxV2=0
C1=0
C2=0
for i in range(0, n -1):
fDescrita= abs(lista[i] - lista[i + 1]) * alt1
maxV1=max(maxV1 + fDescrita, fDescrita)
maxV2 = max(maxV2, maxV1)
alt1 = alt1 * (-1)
#print(fDescrita,maxV1,maxV2)
C1=maxV2
maxV1=0
maxV2=0
alt1=1
for i in range(1, n -1):
fDescrita= abs(lista[i] - lista[i + 1]) * alt1
maxV1=max(maxV1 + fDescrita, fDescrita)
maxV2 = max(maxV2, maxV1)
alt1 = alt1 * (-1)
#print(fDescrita,maxV1,maxV2)
C2=maxV2
print(max(C1,C2)) | 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 math
n=int(input())
a=list(map(int,input().split()))
b=[]
dp1=[]
dp2=[]
c=[]
d=[]
for i in range(n-1):
b.append(abs((a[i+1]-a[i])))
for j in range(n-1):
if(j%2):
c.append(b[j])
d.append(-1*b[j])
else:
c.append(-1*b[j])
d.append(b[j])
dp1.append(c[0])
dp2.append(d[0])
for i in range(1,n-1):
dp1.append(max(c[i],dp1[i-1]+c[i]))
dp2.append(max(d[i],dp2[i-1]+d[i]))
print(max(max(dp1),max(dp2)))
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
public class Main2 {
public static void main(String[] args) throws IOException {
new Main2().solve();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.0000000001;
PrintWriter out;
int n;
int m;
//ArrayList<Integer>[] g = new ArrayList[300000];
int cnt = 0;
void solve() throws IOException {
Reader in;
BufferedReader br;
try {
//br = new BufferedReader( new FileReader("input.txt") );
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
int p1 = 0;
int p2 = 0;
long ans = 0;
long sum = 0;
while (p2 < n-1) {
if (p2%2 == 0)
sum += Math.abs(a[p2 + 1] - a[p2]);
else
sum -= Math.abs(a[p2 + 1] - a[p2]);
ans = Math.max(ans, sum);
if (sum <= 0) {
p1 = p2+1;
p2 = p1;
sum = 0;
}
else
p2++;
}
p1 = 1;
p2 = 1;
sum = 0;
while (p2 < n-1) {
if (p2%2 == 1)
sum += Math.abs(a[p2 + 1] - a[p2]);
else
sum -= Math.abs(a[p2 + 1] - a[p2]);
ans = Math.max(ans, sum);
if (sum <= 0) {
p1 = p2+1;
p2 = p1;
sum = 0;
}
else
p2++;
}
out.println(ans);
out.flush();
out.close();
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a > p.a) return 1;
if (a < p.a) return -1;
return 0;
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
List<Integer> a=new ArrayList<Integer>();
for(int i=0;i<n;i++){
a.add(in.nextInt());
}
long[] f=new long[n];
long[] f1=new long[n];
long l=0,l1=0;
f[0]=0;
f1[0]=0;
for(int i=1;i<n;i++){
if(i%2==1)
f[i]=min(f[i-1]+mod(a.get(i)-a.get(i-1)),mod(a.get(i)-a.get(i-1)));
else
f[i]=min(f[i-1]+(-1)*mod(a.get(i)-a.get(i-1)),(-1)*mod(a.get(i)-a.get(i-1)));
if(i%2==1)
f1[i]=max(f1[i-1]+mod(a.get(i)-a.get(i-1)),mod(a.get(i)-a.get(i-1)));
else
f1[i]=max(f1[i-1]+(-1)*mod(a.get(i)-a.get(i-1)),(-1)*mod(a.get(i)-a.get(i-1)));
l=max(l,mod(f[i]));
l1=max(l1,mod(f1[i]));
}
if(l>l1)
System.out.print(l);
else
System.out.print(l1);
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a<b)
return a;
else
return b;
}
public static long mod(long a){
if(a>0)
return a;
else
return -a;
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int T;
int N;
int A[100101], B[100101];
int main() {
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]);
if (i % 2 == 0) B[i] = -B[i];
}
long long mn = 1000000000000000000, mx = -1000000000000000000,
res = -1000000000000000000;
for (int i = N - 1; i >= 1; i--) {
mn += B[i];
mx += B[i];
mn = min(mn, (long long)B[i]);
mx = max(mx, (long long)B[i]);
if (i % 2) {
res = max(res, mx);
} else {
res = max(res, -mn);
}
}
printf("%lld\n", 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 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.precision(10);
cout << fixed;
srand(time(0));
int n;
cin >> n;
vector<long long> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
vector<long long> a, b;
int c = 1;
for (int i = 0; i < n - 1; i++) {
a.push_back(abs(v[i] - v[i + 1]) * c);
b.push_back(abs(v[i] - v[i + 1]) * -c);
c = -c;
}
long long sum = 0, ans = 0;
for (auto x : a) {
sum = max(sum + x, x);
ans = max(ans, sum);
}
sum = 0;
for (auto x : b) {
sum = max(sum + x, x);
ans = max(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 | import java.util.Scanner;
public class MaxFn {
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();
}
sc.close();
long lmax=Math.abs(a[0]-a[1]);
int sign=-1;
long rmax=sign*lmax;
long lmaxsofar=lmax;
long rmaxsofar=sign*rmax;
for(int i = 1 ; i < a.length-1; i++){
lmax=Math.max(Math.abs(a[i]-a[i+1])*sign, lmax+Math.abs(a[i]-a[i+1])*sign);
lmaxsofar=Math.max(lmaxsofar, lmax);
rmax=Math.max(Math.abs(a[i]-a[i+1])*sign*-1, rmax+Math.abs(a[i]-a[i+1])*sign*-1);
rmaxsofar=Math.max(rmaxsofar, rmax);
sign=sign*-1;
}
System.out.println(Math.max(lmaxsofar, rmaxsofar));
}
}
| 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 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
# def get()
n = int(input())
a = list(map(int,input().split()))
aa = [abs(a[i]-a[i+1]) for i in range(n-1)]
b = [aa[i]*((-1)**i) for i in range(n-1)]
c = [aa[i]*((-1)**(i+1)) for i in range(n-1)]
# print(b)
# print(c)
print(max(maxSubArraySum(b,n-1),maxSubArraySum(c,n-1))) | 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 = 100002;
int n;
long long dp[N], a[N], diffs[N];
int main() {
scanf("%d", &n);
for (int i = (1); i <= (int)(n); ++i) scanf("%lld", &a[i]);
for (int i = (1); i <= (int)(n - 1); ++i) diffs[i] = abs(a[i] - a[i + 1]);
dp[1] = diffs[1], dp[2] = diffs[2];
for (int i = (3); i <= (int)(n); ++i)
dp[i] = diffs[i] + max(0ll, dp[i - 2] - diffs[i - 1]);
long long ans = -1e18;
for (int i = (1); i <= (int)(n); ++i) ans = max(dp[i], ans);
printf("%lld\n", ans);
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 |
import java.io.*;
import java.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static boolean possible(int n , int r,long sum) {
if(sum < (r*(r+1))/2) {
return false;
}
if(sum > ((n*(n+1))/2) - ((n-r)*(n-r+1))/2) {
return false;
}
return true;
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuffer res = new StringBuffer();
int tc = 1;
while(tc-->0) {
int n = sc.nextInt();
long b[] = new long[n];
for(int i=0;i<n;i++) {
b[i] = sc.nextLong();
}
long a[] = new long[n-1];
for(int i=0;i<n-1;i++) {
a[i] = Math.abs(b[i]-b[i+1]);
}
for(int i=0;i<n-1;i+=2) {
a[i] = -a[i];
}
long max1 = a[0];
long cur1 = a[0];
for(int i=1;i<n-1;i++) {
cur1 = Math.max(cur1 + a[i], a[i]);
max1 = Math.max(max1, cur1);
}
for(int i=0;i<n-1;i+=2) {
a[i] = -a[i];
}
for(int i=1;i<n-1;i+=2) {
a[i] = -a[i];
}
long max2 = a[0];
long cur2 = a[0];
for(int i=1;i<n-1;i++) {
cur2 = Math.max(cur2 + a[i], a[i]);
max2 = Math.max(max2, cur2);
}
System.out.println(Math.max(max1, max2));
}
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 |
from math import fabs
n = int(input())
a = list(map(int,input().split(" ")))
a.insert(0,0)
n += 1;
dpmin = [0]*n
dpmax = [0]*n
dpmin[2] = abs(a[2]-a[1])
dpmax[2] = abs(a[2]-a[1])
for i in range(3,n) :
dpmax[i] = max(abs(a[i]-a[i-1]) ,abs(a[i]-a[i-1])-dpmin[i-1] )
dpmin[i] = min(abs(a[i]-a[i-1]) ,abs(a[i]-a[i-1])-dpmax[i-1])
res = 0;
for i in dpmax :
res = max(res,i)
print(res)
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int64_t f(vector<int64_t> v) {
int64_t best = 0;
int64_t curr = 0;
for (int i = 0; i < v.size(); i++) {
curr += v[i];
best = max(best, curr);
if (curr < 0) curr = 0;
}
return best;
}
int main() {
int n;
cin >> n;
vector<int64_t> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
vector<int64_t> d1(n - 1);
for (int i = 0; i + 1 < n; i++) d1[i] = abs(v[i] - v[i + 1]);
vector<int64_t> d2 = d1;
for (int i = 0; i + 1 < n; i++) {
if (i % 2 == 0)
d2[i] *= -1;
else
d1[i] *= -1;
}
cout << max(f(d1), f(d2)) << 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() {
int n;
cin >> n;
long long int a[n + 5];
for (int i = 0; i < (n); i++) cin >> a[i];
long long int x[n + 5], y[n + 5];
for (int i = 0; i < (n - 1); i++) {
long long int z = abs(a[i] - a[i + 1]);
if (i % 2 == 0) {
x[i] = z;
y[i] = -z;
} else {
x[i] = -z;
y[i] = z;
}
}
long long int maximum = -1000000007;
long long int sum = 0;
for (int i = 0; i < (n - 1); i++) {
sum += x[i];
maximum = max(maximum, sum);
if (sum < 0) sum = 0;
}
sum = 0;
for (int i = 0; i < (n - 1); i++) {
sum += y[i];
maximum = max(maximum, sum);
if (sum < 0) sum = 0;
}
cout << maximum << endl;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class FunctionsAgain {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] array = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
array[i] = Integer.parseInt(st.nextToken());
}
int[] absDiff = new int[n];
for (int i = 1; i < n; i++) {
absDiff[i] = Math.abs(array[i] - array[i - 1]);
}
long[][] dp = new long[n][2];
for (int i = 0; i < n; i++) {
dp[i][0] = Long.MIN_VALUE;
dp[i][1] = Long.MIN_VALUE;
}
dp[1][0] = absDiff[1];
long max = absDiff[1];
for (int i = 2; i < n; i++) {
dp[i][1] = Math.max(dp[i][1], dp[i - 1][0] - absDiff[i]);
dp[i][0] = absDiff[i];
if (dp[i - 1][1] != Long.MIN_VALUE) {
dp[i][0] = Math.max(dp[i][0], dp[i - 1][1] + absDiff[i]);
}
max = Math.max(max, dp[i][0]);
max = Math.max(max, dp[i][1]);
}
System.out.println(max);
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class main {
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
private static long max = Long.MIN_VALUE;
private static int mod = 1000000000 + 7;
private static boolean flag=false;
private static int count=0;
private static void soln() {
int n=nextInt();
int[] arr=nextIntArray(n);
long[] diff=new long[n-1];
for(int i=1;i<n;i++){
diff[i-1]=Math.abs(arr[i]-arr[i-1]);
}
long tot=0;
long odd=0;
long max=Long.MIN_VALUE;
TreeSet<Long> e=new TreeSet<>();
e.add(0L);
for(int i=0;i<n-1;i++){
if(i%2==0)
tot+=diff[i];
else
tot-=diff[i];
long ma=e.last();
long mi=e.first();
max=Math.max(Math.abs(tot-ma),max);
max=Math.max(max,Math.abs(tot-mi));
e.add(tot);
}
pw.println(max);
}
public static class Segment {
private long[] tree;
private long[] lazy;
private int size;
//private int[] s;
private int n;
private class node{
private int a;
private int b;
private int c;
public node(int x,int y,int z){
a=x;
b=y;
c=z;
}
}
public Segment(int n){
//this.base=arr;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
size = 2 * (int) Math.pow(2, x) - 1;
tree=new long[size];
lazy=new long[size];
//s=new int[size];
this.n=n;
//build(0,0,n-1);
}
private void build(int id,int l,int r){
//pw.println(1);
if(r==l){
tree[id]=0;
//s[id]=1;
return;
}
int mid=l+(r-l)/2;
//System.out.println(2*id+1+" "+l+" "+mid);
build(2*id+1,l,mid);
//System.out.println(2*id+2+" "+(mid+1)+" "+r);
build(2*id+2,mid+1,r);
//s[id]=s[2*id+1]+s[2*id+2];
//System.out.println(s[id]+" "+(l+1)+" "+(r+1));
}
public long query(int l,int r){
return queryUtil(l,r,0,0,n-1);
}
private long queryUtil(int x,int y,int id,int l,int r){
if(l>y || x>r)
return 0;
System.out.println((l+1)+" "+(r+1)+" "+tree[id]+" "+lazy[id]+" "+1);
shift(id,l,r);
if(x <= l && r<=y)
return tree[id];
int mid=l+(r-l)/2;
System.out.println((l+1)+" "+(r+1)+" "+tree[id]+" "+lazy[id]+" "+2);
return queryUtil(x,y,2*id+1,l,mid)+queryUtil(x,y,2*id+2,mid+1,r);
}
/*private void cnt(int id,int l,int r,HashSet<Integer> set){
if(tree[id]!=0){
set.add(tree[id]);
return;
}
if(r==l)
return;
int mid=l+(r-l)/2;
cnt(2*id+1,l,mid,set);
cnt(2*id+2,mid+1,r,set);
}*/
public void update(int i,int colour,int id,int l,int r){
if(i<l || i>r){
return;
}
if(l==r){
tree[id]=colour;
return;
}
int mid=l+(r-l)/2;
//shift(id);
update(i,colour,2*id+1,l,mid);
update(i,colour,2*id+2,mid+1,r);
tree[id]=Math.max(tree[2*id+1],tree[2*id+2]);
}
public void update(int x,int y,long colour,int id,int l,int r){
if(x>r || l>y){
//tree[id]=s[id]*(lazy[id]);
return;
}
shift(id,l,r);
if(x<=l && r<=y){
tree[id]+=((long)(r-l+1))*colour;
if(l!=r){
lazy[2*id+1]+=colour;
lazy[2*id+2]+=colour;
}
//System.out.println((l+1)+" "+(r+1)+" "+colour+" "+tree[id]+" "+1);
return;
}
int mid=l+((r-l)>>1);
//shift(id);
update(x,y,colour,(id<<1)+1,l,mid);
update(x,y,colour,(id<<1)+2,mid+1,r);
tree[id]+=((long)(Math.min(y,r)-Math.max(x,l)+1))*colour;
//tree[id]=tree[2*id+1]+tree[2*id+2];
//System.out.println((l+1)+" "+(r+1)+" "+colour+" "+tree[id]+" "+2);
}
private void shift(int id,int l,int r){
if(lazy[id]!=0){
if(l!=r){
lazy[2*id+1]+=lazy[id];
lazy[2*id+2]+=lazy[id];
}
tree[id]+=((long)(r-l+1))*lazy[id];
lazy[id]=0;
System.out.println((l+1)+" "+(r+1)+" "+tree[id]+" "+lazy[id]+" "+3);
}
}
}
private static class DSU{
int[] parent;
public DSU(int n){
parent=new int[n];
for(int i=0;i<n;i++)
parent[i]=i;
}
int find(int i){
while(parent[i] !=i){
parent[i]=parent[parent[i]];
i=parent[i];
}
return i;
}
void Union(int x, int y){
int xset = find(x);
int yset = find(y);
parent[yset]=yset;
parent[xset] = yset;
}
}
private static class Edge implements Comparable<Edge>{
int x;
int y;
int w;
public Edge(int a,int b,int c){
x=a; y=b; w=c;
}
@Override
public int compareTo(Edge o) {
return o.w-this.w;
}
}
/*static class Suffix implements Comparable<Suffix>{
int index;
int[] rank=new int[2];
@Override
public int compareTo(Suffix arg0){
return (this.rank[0]==arg0.rank[0])?(this.rank[1]<arg0.rank[1]?-1:1):(this.rank[0]<arg0.rank[0]?-1:1);
}
}
private static int[] buildSuffix(String s,int n){
Suffix[] arr=new Suffix[n];
for(int i=0;i<n;i++)
arr[i]=new Suffix();
for(int i=0;i<n;i++){
arr[i].index=i;
arr[i].rank[0]=s.charAt(i)-'a';
arr[i].rank[1]=((i+1)<n)?(s.charAt(i+1)-'a'):-1;
}
Arrays.sort(arr);
//for(int i=0;i<n;i++)
//System.out.print(arr[i].index);
int[] ind=new int[n];
for(int k=4;k<2*n;k=k*2){
int rank=0;
int p_rank=arr[0].rank[0];
arr[0].rank[0]=rank;
ind[arr[0].index]=0;
for(int i=1;i<n;i++){
if (arr[i].rank[0] == p_rank && arr[i].rank[1] == arr[i-1].rank[1]) {
p_rank = arr[i].rank[0];
arr[i].rank[0] = rank;
}
else{
p_rank = arr[i].rank[0];
arr[i].rank[0] = ++rank;
}
ind[arr[i].index] = i;
}
for(int i=0;i<n;i++){
int n_index=arr[i].index + k/2;
arr[i].rank[1]=(n_index<n)?arr[ind[n_index]].rank[0] : -1;
}
Arrays.sort(arr);
}
int[] suffixArr=new int[n];
for(int i=0;i<n;i++)
suffixArr[i]=arr[i].index;
return suffixArr;
}*/
private static long pow(long a, long b, long c) {
if (b == 0)
return 1;
long p = pow(a, b / 2, c);
p = (p * p) % c;
return (b % 2 == 0) ? p : (a * p) % c;
}
private static class Pair implements Comparable<Pair> {
int x;
int y;
int z;
public Pair(int a,int b,int c) {
x=a;y=b;z=c;
}
@Override
public int compareTo(Pair arg0) {
return (this.x!=arg0.x)?(this.x-arg0.x):((this.y!=arg0.y)?(this.y-arg0.y):(this.z-arg0.z));
}
}
private static int gcd(int a1, int a2) {
if (a2 == 0)
return a1;
return gcd(a2, a1 % a2);
}
private static long max(long a, long b) {
if (a > b)
return a;
return b;
}
private static long min(long a, long b) {
if (a < b)
return a;
return b;
}
public static void main(String[] args) throws Exception {
new Thread(null,new Runnable(){
@Override
public void run() {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
},"1",1<<26).start();
}
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static 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++];
}
private static 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;
}
private static 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;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static 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();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long maxsubsum(vector<int> &vec) {
long long maxsum = 0;
long long cursum = 0;
for (int i = 0; i < vec.size(); i++) {
cursum += vec[i];
if (cursum < 0) cursum = 0;
maxsum = max(maxsum, cursum);
}
return maxsum;
}
int main() {
int n;
cin >> n;
vector<int> vec(n);
vector<int> dif(n - 1);
for (int i = 0; i < n; i++) cin >> vec[i];
for (int i = 0; i < n - 1; i++) dif[i] = abs(vec[i] - vec[i + 1]);
vector<int> dif2 = dif, dif1 = dif;
for (int i = 0; i < n - 1; i += 2) dif1[i] = -dif1[i];
for (int i = 1; i < n - 1; i += 2) dif2[i] = -dif2[i];
cout << max(maxsubsum(dif1), maxsubsum(dif2));
}
| 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 = 100010;
long long dp[2][N], a[N], f[N];
int main() {
int n;
cin >> n;
for (int i = 0; i < (int)n; i++) cin >> a[i];
f[0] = abs(a[0] - a[1]);
for (int i = 1; i < (int)n - 1; i++) {
f[i] = abs(a[i] - a[i + 1]);
}
dp[0][0] = f[0];
dp[1][0] = -1 << 31;
for (int i = 1; i < (int)n - 1; i++) {
dp[0][i] = max(0LL, dp[1][i - 1]) + f[i];
dp[1][i] = max(0LL, dp[0][i - 1]) - f[i];
}
cout << max(*max_element(dp[0], dp[0] + n - 1),
*max_element(dp[1], dp[1] + n - 1))
<< "\n";
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long a[100100], b[100100], c[100100], d[100100];
int main() {
long long n, i, t;
scanf("%I64d", &n);
for (i = 0; i < n; i++) scanf("%I64d", &a[i]);
for (i = 0; i < n - 1; i++) b[i] = abs(a[i] - a[i + 1]);
c[n] = 0;
d[n] = 0;
long long ans = LLONG_MIN;
for (i = n - 1; i >= 0; i--) {
c[i] = b[i] - d[i + 1];
d[i] = b[i] - c[i + 1];
c[i] = max(b[i], c[i]);
ans = max(ans, c[i]);
}
printf("%I64d\n", ans);
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main6{
static class Pair
{
String x;
int y;
public Pair(String x, int y)
{
this.x = x;
this.y = y;
}
}
static class Pair1
{
String x;
int y;
int z;
}
static class Compare
{
static void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.y>p2.y)
{
return -1;
}
else if(p2.y>p1.y)
{
return 1;
}
else
{
return 0;
}
}
});
}
}
public static long pow(long a, long b)
{
long result=1;
while(b>0)
{
if (b % 2 != 0)
{
result=(result*a)%mod;
b--;
}
a=(a*a)%mod;
b /= 2;
}
return result;
}
public static long fact(long num)
{
long value=1;
int i=0;
for(i=2;i<num;i++)
{
value=((value%mod)*i%mod)%mod;
}
return value;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static long lcm(int a,int b)
{
return a * (b / gcd(a, b));
}
public static long sum(int h)
{
return (h*(h+1)/2);
}
public static void dfs(int parent,boolean[] visited)
{
TreeSet<Integer> arr=new TreeSet<Integer>();
arr=graph.get(parent);
visited[parent]=true;
if(a[parent]==1)
{
flag=1;
}
if(a[parent]==2)
{
flag1=1;
}
if(flag==1 && flag1==1)
{
return;
}
Iterator itr=arr.iterator();
while(itr.hasNext())
{
int num=(int)itr.next();
if(visited[num]==false)
{
dfs(num,visited);
}
}
}
static int flag1=0;
static int[] dis;
static ArrayList<Integer> ar3;
static long mod=1000000007L;
static ArrayList<TreeSet<Integer>> graph;
static int[] a;
static int flag=0;
public static void main(String args[])throws IOException
{
// InputReader in=new InputReader(System.in);
// OutputWriter out=new OutputWriter(System.out);
// long a=pow(26,1000000005);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> ar=new ArrayList<>();
ArrayList<String> tmp=new ArrayList<>();
ArrayList<Integer> ar2=new ArrayList<>();
// ArrayList<Integer> ar3=new ArrayList<>();
ArrayList<Integer> ar4=new ArrayList<>();
TreeSet<Integer> ts=new TreeSet<>();
TreeSet<Integer> ts1=new TreeSet<>();
HashMap<Double,Integer> hash=new HashMap<>();
HashMap<Double,Integer> hash1=new HashMap<Double,Integer>();
HashMap<Long,Integer> hash2=new HashMap<Long,Integer>();
/* boolean[] prime=new boolean[10001];
for(int i=2;i*i<=10000;i++)
{
if(prime[i]==false)
{
for(int j=2*i;j<=10000;j+=i)
{
prime[j]=true;
}
//389378484
}
}*/
int n=i();
int[] a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=i();
}
long[] diff=new long[n];
for(int i=0;i<n-1;i++)
{
diff[i]=Math.abs(a[i]-a[i+1]);
}
long[] first=new long[n-1];
long[] second=new long[n-1];
for(int i=0;i<n-1;i++)
{
if(i%2==0)
{
first[i]=diff[i];
second[i]=-diff[i];
}
else
{
first[i]=-diff[i];
second[i]=diff[i];
}
}
long sum=0,max_sum=0;
for(int i=0;i<n-1;i++)
{
sum+=first[i];
if(sum<0)
{
sum=0;
}
else
{
if(sum>max_sum)
{
max_sum=sum;
}
}
}
long ans=0;
ans=Math.max(ans,max_sum);
sum=0;
max_sum=0;
for(int i=0;i<n-1;i++)
{
sum+=second[i];
if(sum<0)
{
sum=0;
}
else
{
if(sum>max_sum)
{
max_sum=sum;
}
}
}
ans=Math.max(ans,max_sum);
pln(ans+"");
}
/**/
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
public static long l()
{
String s=in.String();
return Long.parseLong(s);
}
public static void pln(String value)
{
System.out.println(value);
}
public static int i()
{
return in.Int();
}
public static String s()
{
return in.String();
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars== -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.Int();
return array;
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<long long> data(n + 1);
for (int i = 1; i <= n; i++) {
scanf("%lld", &data[i]);
}
vector<long long> b(n + 1);
vector<long long> c(n + 1);
vector<long long> pref1(n + 1);
vector<long long> pref2(n + 1);
for (int i = 1; i < n; i++) {
b[i] = abs(data[i + 1] - data[i]) * (pow(-1, i));
c[i] = abs(data[i + 1] - data[i]) * (pow(-1, i + 1));
}
pref1[1] = b[1];
pref2[1] = c[1];
for (int i = 2; i <= n; i++) {
pref1[i] = pref1[i - 1] + b[i];
pref2[i] = pref2[i - 1] + c[i];
}
long long bMax = *max_element(pref1.begin(), pref1.end());
long long cMax = *max_element(pref2.begin(), pref2.end());
printf("%lld", cMax + bMax);
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;
vector<long long int> v1, v2, v;
long long int res = -1000000000000000000;
int n;
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
long long int x;
cin >> x;
v.push_back(x);
}
for (unsigned long long int i = 0; i < v.size() - 1; i++) {
long long int x = (abs(v[i] - v[i + 1])) * (i % 2 ? 1 : -1);
v1.push_back(x);
v2.push_back(-x);
}
long long int max_ending_here = 0;
for (unsigned long long int i = 0; i < v1.size(); i++) {
max_ending_here = max_ending_here + v1[i];
if (res < max_ending_here) res = max_ending_here;
if (max_ending_here < 0) max_ending_here = 0;
}
max_ending_here = 0;
for (unsigned long long int i = 0; i < v2.size(); i++) {
max_ending_here = max_ending_here + v2[i];
if (res < max_ending_here) res = max_ending_here;
if (max_ending_here < 0) max_ending_here = 0;
}
cout << res;
}
| 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(0);
cin.tie(0);
cout.tie(0);
long long n = 0, ans = 0;
cin >> n;
vector<long long> a(n), f1(n), f2(n);
for (long long i = 0; i < n; i++) {
cin >> a[i];
if (i) {
f1[i] = abs(a[i] - a[i - 1]) * pow(-1, i + 1);
f2[i] = -f1[i];
}
}
ans = f1[1];
long long cur = f1[1];
int l = 1;
for (int i = 2; i < n; i++) {
cur += f1[i];
while (l <= i && cur < 0) cur -= f1[l++];
ans = max(ans, cur);
}
if (n > 2) {
cur = f2[2];
ans = max(ans, cur);
l = 2;
for (int i = 3; i < n; i++) {
cur += f2[i];
while (l <= i && cur < 0) cur -= f2[l++];
ans = max(ans, cur);
}
}
cout << ans;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
import java.io.*;
public final class CF {
static long ans(long[] a) {
long max = Integer.MIN_VALUE;
long curr = 0;
for(int i = 0; i<a.length; i++) {
curr+=a[i];
if(max<curr)
max = curr;
if(curr<0)
curr = 0;
}
return max;
}
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();
long[] a1 = new long[n];
long[] a2 = new long[n];
int j = 1;
for(int i = 0; i<n-1; i++) {
a1[i] = 1l*Math.abs(a[i]-a[i+1])*j;
j*=-1;
}
for(int i = 0; i<n; i++)
a2[i] = -a1[i];
System.out.println(Math.max(ans(a1), ans(a2)));
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long N, A[100005];
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> N;
for (int i = int(1); i < int(N + 1); i++) cin >> A[i];
long long best = 0, acc = 0;
for (int i = int(1); i < int(N); i++) {
acc += abs(A[i] - A[i + 1]) * (i % 2 == 1 ? 1 : -1);
if (acc > best) best = acc;
if (acc < 0) acc = 0;
}
acc = 0;
for (int i = int(2); i < int(N); i++) {
acc += abs(A[i] - A[i + 1]) * (i % 2 == 0 ? 1 : -1);
if (acc > best) best = acc;
if (acc < 0) acc = 0;
}
cout << best << '\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 binpow(long long a, long long b, long long m) {
a %= m;
long long res = 1;
while (b > 0) {
if (b & 1) res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
struct Sieve {
long long n;
vector<long long> primes, f;
Sieve(long long nn) {
n = nn;
f.resize(n + 1);
f[0] = f[1] = -1;
for (long long i = 2; i <= n; i++) {
if (!f[i]) {
primes.push_back(i);
f[i] = i;
for (long long j = 2 * i; j <= n; j += i) {
if (!f[j]) f[j] = i;
}
}
}
}
bool check(long long x) { return f[x] == x; }
vector<pair<long long, long long>> factor_vec(long long x) {
vector<pair<long long, long long>> ret;
while (x != 1) {
if (ret.empty() or ret.back().first != f[x]) {
ret.emplace_back(f[x], 1);
} else {
ret.back().second++;
}
x /= f[x];
}
return ret;
}
map<long long, long long> factor_map(long long x) {
map<long long, long long> ret;
while (x != 1) {
ret[f[x]]++;
x /= f[x];
}
return ret;
}
long long divisors(long long x) {
long long ret = 1;
for (auto [x, y] : factor_vec(x)) {
ret *= (y + 1);
}
return ret;
}
};
long long binpow(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1) res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
struct LCA {
vector<vector<long long>> par;
vector<long long> dep;
long long n;
LCA(vector<vector<long long>> &t) {
n = t.size();
par.assign(t.size() + 1, vector<long long>(20));
dep.resize(n + 1);
dfs(t, 1, 0, 1);
}
void dfs(vector<vector<long long>> &t, long long u, long long fa,
long long d) {
for (long long i = 1; i < 20; ++i) par[u][i] = par[par[u][i - 1]][i - 1];
dep[u] = d;
for (long long i = 0; i < t[u].size(); ++i) {
long long v = t[u][i];
if (v == fa) continue;
par[v][0] = u;
dfs(t, v, u, d + 1);
}
}
long long lca(long long x, long long y) {
if (dep[x] < dep[y]) swap(x, y);
long long d = dep[x] - dep[y];
for (long long i = 17; i >= 0; --i)
if (d >> i & 1) x = par[x][i];
if (x == y) return x;
for (long long i = 17; i >= 0; --i) {
if (par[x][i] == par[y][i]) continue;
x = par[x][i], y = par[y][i];
}
return par[x][0];
}
long long dis(long long a, long long b) {
long long fa = lca(a, b);
return dep[a] + dep[b] - 2 * dep[fa];
}
};
void coordinate_compress(vector<long long> &a) {
vector<long long> b = a;
sort(b.begin(), b.end());
map<long long, long long> m;
long long n = a.size();
for (long long i = 0; i < n; i++) {
m[b[i]] = i;
}
for (long long i = 0; i < n; i++) {
a[i] = m[a[i]];
}
}
vector<long long> sort_cyclic_shifts(string const &s) {
long long n = s.size();
const long long alphabet = 256;
vector<long long> p(n), c(n), cnt(max(alphabet, n), 0);
for (long long i = 0; i < n; i++) cnt[s[i]]++;
for (long long i = 1; i < alphabet; i++) cnt[i] += cnt[i - 1];
for (long long i = 0; i < n; i++) p[--cnt[s[i]]] = i;
c[p[0]] = 0;
long long classes = 1;
for (long long i = 1; i < n; i++) {
if (s[p[i]] != s[p[i - 1]]) classes++;
c[p[i]] = classes - 1;
}
vector<long long> pn(n), cn(n);
for (long long h = 0; (1 << h) < n; ++h) {
for (long long i = 0; i < n; i++) {
pn[i] = p[i] - (1 << h);
if (pn[i] < 0) pn[i] += n;
}
fill(cnt.begin(), cnt.begin() + classes, 0);
for (long long i = 0; i < n; i++) cnt[c[pn[i]]]++;
for (long long i = 1; i < classes; i++) cnt[i] += cnt[i - 1];
for (long long i = n - 1; i >= 0; i--) p[--cnt[c[pn[i]]]] = pn[i];
cn[p[0]] = 0;
classes = 1;
for (long long i = 1; i < n; i++) {
pair<long long, long long> cur = {c[p[i]], c[(p[i] + (1 << h)) % n]};
pair<long long, long long> prev = {c[p[i - 1]],
c[(p[i - 1] + (1 << h)) % n]};
if (cur != prev) ++classes;
cn[p[i]] = classes - 1;
}
c.swap(cn);
}
return p;
}
vector<long long> suffix_array_construction(string s) {
s += "$";
vector<long long> sorted_shifts = sort_cyclic_shifts(s);
sorted_shifts.erase(sorted_shifts.begin());
return sorted_shifts;
}
vector<long long> lcp_construction(string const &s,
vector<long long> const &p) {
long long n = s.size();
vector<long long> rank(n, 0);
for (long long i = 0; i < n; i++) rank[p[i]] = i;
long long k = 0;
vector<long long> lcp(n - 1, 0);
for (long long i = 0; i < n; i++) {
if (rank[i] == n - 1) {
k = 0;
continue;
}
long long j = p[rank[i] + 1];
while (i + k < n && j + k < n && s[i + k] == s[j + k]) k++;
lcp[rank[i]] = k;
if (k) k--;
}
return lcp;
}
vector<long long> z_function(string const &s) {
long long n = (long long)s.length();
vector<long long> z(n);
for (long long i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r) z[i] = min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i];
if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1;
}
return z;
}
signed main() {
long long n;
cin >> n;
vector<long long> arr(n);
for (long long i = 0; i < n; i++) {
cin >> arr[i];
}
vector<long long> brr;
long long parity = 1;
for (long long i = 1; i < n; i++) {
brr.push_back(abs(arr[i] - arr[i - 1]) * parity);
parity *= -1;
}
long long ans = LONG_MIN;
long long sum = 0;
for (long long i = 0; i < brr.size(); i++) {
sum += brr[i];
ans = max(ans, sum);
if (sum < 0) sum = 0;
}
for (long long i = 0; i < brr.size(); i++) {
brr[i] *= -1;
}
sum = 0;
for (long long i = 0; i < brr.size(); i++) {
sum += brr[i];
ans = max(ans, sum);
if (sum < 0) sum = 0;
}
cout << ans << "\n";
;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
public class cf407c {
static final int N=(int)1e5+10;
static final long inf=(long)1e10;
static int a[]=new int[N];
static int b[]=new int[N];
static int c[]=new int[N];
public static void main(String[] args){
Scanner cin=new Scanner(new InputStreamReader(System.in));
while(cin.hasNext()){
int n=cin.nextInt();
for(int i =0; i<n; i++){
a[i]=cin.nextInt();
}
int tmp;
for(int i=0;i<n-1;i++){
tmp=Math.abs(a[i]-a[i+1]);
if(i%2==0){
b[i]=tmp;
c[i]=-tmp;
}else{
b[i]=-tmp;
c[i]=tmp;
}
}
long ans1=-inf,ans2=-inf;
long sum=0;
for(int i=0;i<n-1;i++){
sum+=b[i];
ans1=Math.max(ans1, sum);
if(sum<0){
sum=0;
}
}
sum=0;
for(int i=0;i<n-1;i++){
sum+=c[i];
ans2=Math.max(ans2, sum);
if(sum<0){
sum=0;
}
}
System.out.println(Math.max(ans1, ans2));
}
cin.close();
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
long long N;
cin >> N;
long long v[N];
for (long long i = 0; i < N; i++) cin >> v[i];
long long arr1[N - 1], arr2[N - 1];
for (long long i = 0; i < N - 1; i++) {
arr1[i] = -1 * abs(v[i + 1] - v[i]);
arr2[i] = abs(v[i + 1] - v[i]);
if (i & 1) swap(arr1[i], arr2[i]);
}
long long max1[N - 1], max2[N - 1];
max1[0] = arr1[0];
max2[0] = arr2[0];
for (long long i = 1; i < N - 1; i++)
max1[i] = max(max1[i - 1] + arr1[i], arr1[i]);
for (long long i = 1; i < N - 1; i++)
max2[i] = max(max2[i - 1] + arr2[i], arr2[i]);
long long ans = 0;
for (long long i = 0; i < N - 1; i++) ans = max(ans, max(max1[i], max2[i]));
cout << ans;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
int i = 0, j = 0, cs = 0, in;
int n;
cin >> n;
vector<int> v, a, b;
for (i = 0; i < n; i++) {
cin >> in;
v.push_back(in);
};
for (i = 0; i < n - 1; i++) {
int x = abs(v[i + 1] - v[i]);
if (i & 1)
a.push_back(-1 * x), b.push_back(x);
else
a.push_back(x), b.push_back(-1 * x);
}
long long ma = 0, mb = 0;
long long cnt = 0;
for (i = 0; i < a.size(); i++) {
cnt += a[i];
if (cnt < 0) cnt = 0;
ma = max(ma, cnt);
}
cnt = 0;
for (i = 0; i < b.size(); i++) {
cnt += b[i];
if (cnt < 0) cnt = 0;
mb = max(mb, cnt);
}
cout << max(ma, mb) << "\n";
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = int(1e5) + 5;
int n;
int a[N];
long long dp[N];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 1; i <= n; cin >> a[i++])
;
for (int i = 1; i <= n - 1; i++) a[i] = abs(a[i] - a[i + 1]);
dp[1] = (long long)a[1];
for (int i = 2; i <= n - 1; i++) {
if (i % 2 == 0)
dp[i] = dp[i - 1] - (long long)a[i];
else
dp[i] = dp[i - 1] + (long long)a[i];
}
sort(dp, dp + n);
cout << dp[n - 1] - dp[0] << '\n';
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception addd) {
addd.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static FastReader sc = new FastReader();
static long mod = (long) (1e9+7),MAX=(long)(1e6+10);
static List<Integer>[] edges;
static char[] s,t;
public static void main(String[] args) throws IOException{
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) a[i]=sc.nextInt();
long dp1[]=new long[n-1];
long dp2[]=new long[n-1];
int f1=1,f2=-1;
for(int i=1;i<n;i++){
long diff=Math.abs(a[i]-a[i-1]);
dp1[i-1]=f1*diff;
dp2[i-1]=f2*diff;
f1*=-1;
f2*=-1;
}
out.print(Math.max(f(dp1), f(dp2)));
out.close();
}
static long f(long dp[]){
long max=dp[0],sum=dp[0];
for(int i=1;i<dp.length;i++){
sum=Math.max(sum+dp[i],dp[i]);
max=Math.max(max,sum);
}
return max;
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
vector<long long> arr(n + 1, 0);
for (long long i = 1; i <= n; i++) cin >> arr[i];
vector<long long> val(n + 1, 0);
for (long long i = 1; i < n; i++) {
if (i % 2 == 0)
val[i] = abs(arr[i] - arr[i + 1]) * -1;
else
val[i] = abs(arr[i] - arr[i + 1]);
}
long long sum = 0, maxi = LLONG_MIN;
for (long long i = 1; i < val.size(); i++) {
sum += val[i];
maxi = max(maxi, sum);
if (sum < 0) sum = 0;
}
sum = 0;
for (long long i = 1; i < val.size(); i++) {
sum += -1 * val[i];
maxi = max(maxi, sum);
if (sum < 0) sum = 0;
}
cout << maxi;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class codeforces
{
static class Student{
int e,l;
Student(int e,int l){
this.e=e;
this.l=l;
}
}
static int sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
int pos=0;
boolean prime[] = new boolean[n+1];
for(int i=0;i<=n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
// If prime[p] is not changed, then it is a prime
if(prime[p] == true)
{
// Update all multiples of p
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for(int i = 2; i <= n; i++)
{
if(prime[i] == true)
++pos;
}
return pos;
}
/*static class Sortbyroll implements Comparator<Student>
{
// Used for sorting in ascending order of
// roll number
public int compare(Student c, Student b)
{
if(c.s>b.s)
return -1;
else if(c.s==b.s){
if(c.gd>b.gd)
return -1;
else if(c.gd==b.gd){
if(c.gs>b.gs)
return -1;
else if(c.gs==b.gs){
if(c.a>b.a)
return -1;
else
return 1;
}
}
else
return 1;
}
return 1;
}
} */
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static class Edge{
int a,b;
Edge(int a,int b){
this.a=a;
this.b=b;
}
}
public static void main(String[] args){
//long sum=0;
int t,n,d,p,r,j,c_0=-1,c_1=-1,si=0,i,ans2=0,e,mid,min,h,c_2,max,m,pos,temp1,temp2,x,y,c=0,temp,q;
//long ans=0,ans1=0,c_a=0,c_b=0,m,pos,a,b,x,y,z,temp,c;
long a1=0,a2=0,ans=1,sum=0,b;
String s1;
FastReader sc=new FastReader();
n=sc.nextInt();
int a[]=new int[n];
for(i=0;i<n;i++)
a[i]=sc.nextInt();
long dp[][]=new long[n-1][2];
long ch[]=new long[n-1];
for(i=0;i<n-1;i++){
ch[i]=Math.abs(a[i]-a[i+1]);
}
dp[n-2][0]=ch[n-2];
dp[n-2][1]=-ch[n-2];
for(i=n-3;i>=0;i--){
dp[i][0]=Math.max(ch[i],ch[i]+dp[i+1][1]);
dp[i][1]=Math.max(-ch[i],-ch[i]+dp[i+1][0]);
}
ans=Integer.MIN_VALUE;
for(i=n-2;i>=0;i--){
ans=Math.max(ans,Math.max(dp[i][0],dp[i][1]));
}
System.out.println(ans);
}
static long power(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & (long)1)%2!=0)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res%p;
}
static int find(int x,int parent[])
{
// Finds the representative of the set
// that x is an element of
if (parent[x]!=x)
{
// if x is not the parent of itself
// Then x is not the representative of
// his set,
parent[x] = find(parent[x],parent);
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return parent[x];
}
static void union(int x, int y,int rank[],int parent[])
{
// Find representatives of two sets
int xRoot = find(x,parent), yRoot = find(y,parent);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
parent[yRoot] = xRoot;
else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long mod = 1000000007;
inline long long mpow(long long b, long long ex) {
if (b == 1) return 1;
long long r = 1;
while (ex) {
if (ex & 1) r = (r * b) % mod;
ex = ex >> 1;
b = (b * b) % mod;
}
return r;
}
long long n, m, k;
long long b1, q, l;
int main() {
ios_base::sync_with_stdio(0);
cin >> n;
std::vector<long long> a(n + 1, 0), d(n + 1, 0);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
d[n - 1] = abs(a[n - 1] - a[n]);
long long ans = d[n - 1];
for (int i = n - 2; i > 0; --i) {
d[i] = abs(a[i] - a[i + 1]) + max(0LL, d[i + 2] - abs(a[i + 1] - a[i + 2]));
ans = max(d[i], ans);
}
cout << ans << "\n";
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.Scanner;
import java.util.Arrays;
public class Main{
static final long INF = Long.MAX_VALUE / 2;
static int n;
static int[] a;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
a = new int[n];
for(int i = 0; i < n; i++){
a[i] = sc.nextInt();
}
long[] d = new long[n - 1];
for(int i = 0; i + 1 < n; i++){
d[i] = Math.abs(a[i] - a[i + 1]);
}
int m = n - 1;
long[][] max = new long[m + 1][2];
long[][] min = new long[m + 1][2];
max[0][0] = max[0][1] = -INF;
min[0][0] = min[0][1] = INF;
for(int i = 1; i <= m; i++){
max[i][0] = max[i - 1][1] - d[i - 1];
max[i][1] = Math.max(d[i - 1], max[i - 1][0] + d[i - 1]);
min[i][0] = min[i - 1][1] - d[i - 1];
min[i][1] = Math.min(d[i - 1], min[i - 1][0] + d[i - 1]);
}
long ans = 0;
for(int i = 1; i <= m; i++){
ans = Math.max(ans, Math.max(max[i][0], max[i][1]));
}
System.out.println(ans);
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | # import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
# sys.stdin=open('input.txt','r')
# sys.stdout=open('output.txt','w')
input=sys.stdin.readline
# sys.setrecursionlimit(300010)
MOD = 1000000007
MOD2 = 998244353
ii = lambda: int(input().strip('\n'))
si = lambda: input().strip('\n')
dgl = lambda: list(map(int,input().strip('\n')))
f = lambda: map(int, input().strip('\n').split())
il = lambda: list(map(int, input().strip('\n').split()))
ls = lambda: list(input().strip('\n'))
lsi = lambda: [int(i) for i in ls()]
let = 'abcdefghijklmnopqrstuvwxyz'
def kadaneneg(arr,n):
mx = -10**16
mxend=0
for i in range(n):
mxend+=arr[i]
if mxend>mx:
mx=mxend
if mxend<0:
mxend=0
return mx
for _ in range(1):
n=ii()
l=il()
for i in range(n-1):
if i&1:l[i]=(-1)*abs(l[i]-l[i+1])
else:l[i]=abs(l[i]-l[i+1])
l=l[:n-1]
l2=[-1*i for i in l]
mx1=kadaneneg(l[:n-1],n-1)
mx2=kadaneneg(l2[:n-1],n-1)
print(max(mx1,mx2)) | 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 | #!/usr/bin/python
# coding: utf-8
n=int(raw_input())
arr=map(long,raw_input().split(' '))
arr1=[]
arr2=[]
for i in xrange(n-1):
tmp=abs(arr[i+1]-arr[i])
tmp1=tmp*((-1)**i)
arr1.append(tmp1)
tmp2=tmp*((-1)**(i+1))
arr2.append(tmp2)
max1=max2=current1=current2=0
for i in xrange(n-1):
current1+=arr1[i]
current2+=arr2[i]
if(current1<0):
current1=0
if(max1<current1):
max1=current1
if(current2<0):
current2=0
if(max2<current2):
max2=current2
if(max1<max2):
print max2
else:
print max1
'''
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the
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 | #include <bits/stdc++.h>
using namespace std;
long long mm = 1000000007;
long long powe(long long a, long long n) {
long long ans = 1;
while (n) {
if (n & 1) ans = (ans * a) % mm;
n = n / 2;
a = (a * a) % mm;
}
return ans;
}
long long fac[100005];
void precum() {
fac[0] = 1;
for (long long i = 1; i < (100002); ++i) {
fac[i] = (fac[i - 1] * i) % mm;
}
}
long long fun(long long a[], long long n) {
long long maxx = 0, sum = 0;
for (long long i = 0; i < (n); ++i) {
sum += a[i];
if (maxx < sum) {
maxx = sum;
}
if (sum < 0) sum = 0;
}
return maxx;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long t;
t = 1;
while (t--) {
long long n;
cin >> n;
long long a[n - 1], b[n];
for (long long i = 0; i < (n); ++i) {
cin >> b[i];
if (i != 0) a[i - 1] = abs(b[i] - b[i - 1]);
if (i != 0 && i % 2 == 0) a[i - 1] = -a[i - 1];
}
long long ans = fun(a, n - 1);
for (long long i = 0; i < (n - 1); ++i) {
a[i] = -a[i];
}
ans = max(ans, fun(a, n - 1));
cout << ans << '\n';
}
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | from sys import stdin
rints = lambda: [int(x) for x in stdin.readline().split()]
n, a, ans, tem1, tem2 = int(input()), rints(), 0, 0, 0
diff = [abs(a[i] - a[i - 1]) for i in range(1, n)]
for i in range(n - 1):
if i % 2 == 0:
tem1 += diff[i]
tem2 -= diff[i]
if tem2 < 0:
tem2 = 0
else:
tem2 += diff[i]
tem1 -= diff[i]
if tem1 < 0:
tem1 = 0
ans = max(ans, tem1, tem2)
print(ans)
| PYTHON |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
long max=0, up=scan.nextLong(), abs=0, max2=0, temp=0, dif=0;
for (int i=0; i<n-1; i++) {
long down = scan.nextLong();
abs = Math.abs(up - down);
up = down;
temp = max2;
max2 = Math.max(abs, abs+dif);
max = Math.max(max, max2);
dif = temp - abs;
}
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.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.StringTokenizer;
public class Div2407C
{
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[64]; // 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 void main(String[] args) throws IOException
{
Reader sc=new Reader();
int n = sc.nextInt();
long arr[] = new long[n+1];
for(int i=0;i<n;i++) {
arr[i+1] = sc.nextInt();
}
long brr[] = new long[n-1];
long crr[] = new long[n-1];
for(int i=1;i<n;i++) {
brr[i-1] = Math.abs((arr[i]-arr[i+1]))*((long)(Math.pow(-1,i)));
crr[i-1] = Math.abs((arr[i]-arr[i+1]))*((long)(Math.pow(-1,i-1)));
}
//brr = new long[]{-1, -2, -3, -4};
if(n==2)
System.out.println(crr[0]);
else {
long res = max(brr, n-1);
long res1 = max(crr, n-1);
System.out.println(res > res1 ? res: res1);
}
}
public static long max(long brr[], int size) {
long max_so_far = 0, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + brr[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
} | 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.InputStreamReader;
import java.util.StringTokenizer;
public class R407Div2C {
public static void main(String[] args) {
FastScanner in=new FastScanner();
int n=in.nextInt();
int[] a=new int[n-1];
int b=in.nextInt(),c=0;
for(int i=0;i<n-1;i++){
c=in.nextInt();
a[i]=Math.abs(b-c);
b=c;
}
long sum=a[0];
long max1=a[0];
for(int i=1;i<n-1;i++){
if(sum>0){
sum+=i%2==0?a[i]:-a[i];
}else{
sum=i%2==0?a[i]:-a[i];
}
if(sum>max1)
max1=Math.abs(sum);
}
sum=-a[0];
long max2=-a[0];
for(int i=1;i<n-1;i++){
if(sum>0){
sum+=i%2==0?-a[i]:a[i];
}else{
sum=i%2==0?-a[i]:a[i];
}
if(sum>max2)
max2=Math.abs(sum);
}
System.out.println(Math.max(max1,max2));
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));}
String nextToken(){
while(st==null||!st.hasMoreElements())
try{st=new StringTokenizer(br.readLine());}catch(Exception e){}
return st.nextToken();
}
int nextInt(){return Integer.parseInt(nextToken());}
long nextLong(){return Long.parseLong(nextToken());}
double nextDouble(){return Double.parseDouble(nextToken());}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long int maxsum(vector<long long int> a) {
long long int max_so_far = -1000000000000, max_ending_here = 0;
for (int i = 0; i < a.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;
}
int main() {
int n;
cin >> n;
vector<long long int> v;
for (int i = 0; i < n; i++) {
long long int temp = 0;
cin >> temp;
v.push_back(temp);
}
vector<long long int> temp1, temp2;
int j = 0, m = 0;
for (int i = 1; i < v.size(); i++) {
temp1.push_back(abs(v[i] - v[i - 1]));
temp2.push_back(abs(v[i] - v[i - 1]));
}
for (int i = 0; i < temp1.size(); i++) {
if (i % 2 == 0)
temp1[i] = temp1[i] * -1;
else
temp2[i] = temp2[i] * -1;
}
cout << max(maxsum(temp1), maxsum(temp2)) << "\n";
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const long long lnf = (1LL << 61);
int n;
int* a;
long long sodd = 0, suodd = 0;
long long great[2][2] = {{lnf, -lnf}, {lnf, -lnf}};
long long res = -0x3fffffff;
inline void init() {
scanf("%d", &n);
a = new int[(const int)(n + 1)];
for (int i = 1; i <= n; i++) scanf("%d", a + i);
for (int i = 1; i < n; i++) a[i] = abs(a[i + 1] - a[i]);
}
inline void solve() {
if (n == 2) {
printf("%d\n", a[1]);
return;
}
great[0][0] = great[0][1] = 0;
for (int i = 1; i < n; i++) {
if (i & 1) {
sodd += a[i];
long long c = sodd - suodd;
(res) = max((res), (c - great[0][0]));
(res) = max((res), (great[1][1] - c));
(great[1][1]) = max((great[1][1]), (c));
} else {
suodd += a[i];
long long c = sodd - suodd;
(res) = max((res), (c - great[0][0]));
(res) = max((res), (great[1][1] - c));
(great[0][0]) = min((great[0][0]), (c));
}
}
printf("%I64d", res);
}
int main() {
init();
solve();
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<long> a(n);
for (int i = 0; i < n; i++) {
long x;
cin >> x;
a[i] = x;
}
long long b[n], c[n];
for (int i = 0; i < n - 1; i++) {
b[i] = abs(a[i] - a[i + 1]);
c[i] = b[i];
if (i % 2 == 0) {
b[i] = -1 * b[i];
} else {
c[i] = -1 * c[i];
}
}
long long ans = 0;
for (int i = 1; i < n - 1; i++) {
b[i] = max(b[i], b[i] + b[i - 1]);
c[i] = max(c[i], c[i] + c[i - 1]);
}
for (int i = 0; i < n - 1; i++) {
long long x = max(b[i], c[i]);
ans = max(x, ans);
}
cout << ans;
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
import java.math.*;
import java.io.*;
import java.text.*;
public class A{
static class Node{
int x;
long cost;
public Node(int x,long cost) {
this.x=x;
this.cost=cost;
}
}
//public static PrintWriter pw;
public static PrintWriter pw=new PrintWriter(System.out);
public static void solve() throws IOException{
// pw=new PrintWriter(new FileWriter("C:\\Users\\shree\\Downloads\\small_output_in"));
FastReader sc=new FastReader();
int n=sc.I();
long a[]=new long[n];
long sum[]=new long[n];
for(int i=0;i<n;i++)a[i]=sc.L();
for(int i=0;i<n-1;i++) {
sum[i]=Math.abs(a[i+1]-a[i]);
}
long ans1=0,ans2=0,mx=0;
for(int i=0;i<n;i++) {
if(i%2==0) {
ans1+=sum[i];
ans2-=sum[i];
}else {
ans1-=sum[i];
ans2+=sum[i];
}
mx=Math.max(ans1, Math.max(ans2, mx));
if(ans1<0) ans1=0;
if(ans2<0) ans2=0;
}
pw.println(mx);
pw.close();
}
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 long M=(long)Math.pow(10,9)+7;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException{
//br=new BufferedReader(new FileReader("C:\\Users\\shree\\Downloads\\B-small-practice.in"));
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 I(){ return Integer.parseInt(next()); }
long L(){ return Long.parseLong(next()); }
double D() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long f[100005];
long long input[100005];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &input[i]);
}
for (int i = 1; i < n; i++) {
f[i - 1] = input[i - 1] - input[i];
f[i - 1] = labs(f[i - 1]);
}
long long last = 0;
long long result = 0;
for (int i = n - 2; i >= 0; i--) {
if (i % 2 == 1) continue;
long long right = i + 1 <= n - 2 ? -f[i + 1] : 0;
last = max(f[i], f[i] + right + last);
result = max(last, result);
}
last = 0;
for (int i = n - 2; i >= 1; i--) {
if (i % 2 == 0) continue;
long long right = i + 1 <= n - 2 ? -f[i + 1] : 0;
last = max(f[i], f[i] + right + last);
result = max(last, result);
}
printf("%I64d\n", result);
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class CTask {
public static void main(String[] args) throws IOException {
MyInputReader in = new MyInputReader(System.in);
int n = in.nextInt();
long[] arr = new long[n];
long[][] cum = new long[n][2];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
for (int i = 0; i < n - 1; i++) {
long mult = i % 2 == 0 ? 1 : -1;
cum[i][0] = Math.abs(arr[i] - arr[i + 1]) * mult;
cum[i][1] = -Math.abs(arr[i] - arr[i + 1]) * mult;
}
long mx = 0;
long curLeft = 0;
long curRight = 0;
for (int i = 0; i < n - 1; i++) {
curLeft += cum[i][0];
curRight += cum[i][1];
if (curLeft < 0) {
curLeft = 0;
}
if (curRight < 0) {
curRight = 0;
}
mx = Math.max(Math.max(mx, curLeft), curRight);
}
System.out.println(mx);
}
static class MyInputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public MyInputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | 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=input()
nums=map(int,raw_input().split());dp=[0]*(n-1);dp2=[0]*(n-1)
for i in xrange(n-1):
dp[i]=abs(nums[i]-nums[i+1])*(-1)**i
dp2[i]=-dp[i]
best=0;tot=0;best2=0;tot2=0
for i in xrange(n-1):
tot=max(dp[i],tot+dp[i]);tot2=max(dp2[i],tot2+dp2[i])
best=max(best,tot);best2=max(best2,tot2)
print max(best,best2)
| 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;
void solve() {
int n;
cin >> n;
vector<long long> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n - 1; i++) a[i] = abs(a[i] - a[i + 1]);
vector<pair<long long, long long>> dp(n);
long long ans = a[0];
dp[0] = {a[0], -1e17};
for (int i = 1; i < n - 1; i++) {
long long cur = max(a[i], dp[i - 1].second + a[i]);
long long cur_ = max(a[i - 1] - a[i], dp[i - 1].first - a[i]);
dp[i] = {cur, cur_};
ans = max(ans, max(cur, cur_));
}
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int 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 | import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class A extends PrintWriter {
void run() {
int n = nextInt(), m = n - 1;
int[] a = nextArray(n);
long[] s = new long[n];
for (int i = 1, sign = 1; i < n; i++, sign *= -1) {
s[i] = s[i - 1] + sign * abs(a[i] - a[i - 1]);
}
long[] min = new long[n], max = new long[n];
min[m] = max[m] = s[m];
for (int i = m - 1; i >= 0; i--) {
max[i] = max(max[i + 1], s[i]);
min[i] = min(min[i + 1], s[i]);
}
long ans = Long.MIN_VALUE;
for (int i = 1; i < n; i++) {
ans = max(ans, abs(a[i] - a[i - 1]));
}
for (int i = 0, sign = 1; i < m; i++, sign *= -1) {
if (sign < 0) {
ans = max(ans, s[i] - min[i + 1]);
} else {
ans = max(ans, max[i + 1] - s[i]);
}
}
println(ans);
}
boolean skip() {
while (hasNext()) {
next();
}
return true;
}
int[][] nextMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
return matrix;
}
String next() {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
}
int[] nextArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException err) {
return null;
}
}
public A(OutputStream outputStream) {
super(outputStream);
}
static BufferedReader reader;
static StringTokenizer tokenizer = new StringTokenizer("");
static Random rnd = new Random();
static boolean OJ;
public static void main(String[] args) throws IOException {
OJ = System.getProperty("ONLINE_JUDGE") != null;
A solution = new A(System.out);
if (OJ) {
reader = new BufferedReader(new InputStreamReader(System.in));
solution.run();
} else {
reader = new BufferedReader(new FileReader(new File(A.class.getName() + ".txt")));
long timeout = System.currentTimeMillis();
while (solution.hasNext()) {
solution.run();
solution.println();
solution.println("----------------------------------");
}
solution.println("time: " + (System.currentTimeMillis() - timeout));
}
solution.close();
reader.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;
int64_t calc(vector<int64_t> &v) {
int64_t tec = 0, mx = 0;
for (int64_t i = 0; i < v.size(); ++i) {
if (tec < 0) tec = 0;
tec += v[i];
if (tec > mx) mx = tec;
}
return mx;
}
int32_t main() {
ios_base::sync_with_stdio(false);
int64_t n;
cin >> n;
vector<int64_t> u(n), v, d;
for (int64_t i = 0; i < n; ++i) cin >> u[i];
for (int64_t i = 0; i < n - 1; ++i) {
int64_t a = abs(u[i] - u[i + 1]);
if (i % 2) {
v.push_back(a);
d.push_back(-a);
} else {
v.push_back(-a);
d.push_back(a);
}
}
cout << max(calc(v), calc(d));
}
| 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 + 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() {
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 | from sys import stdin
from itertools import repeat
def main():
n = int(stdin.readline())
a = map(int, stdin.readline().split(), repeat(10, n))
b = map(abs, [a[i+1] - a[i] for i in xrange(n - 1)])
ans = max(b)
b[1::2] = [-x for x in b[1::2]]
c = t = 0
for x in b:
c += x
if t > c:
t = c
if ans < c - t:
ans = c - t
b = [-x for x in b][1:]
c = t = 0
for x in b:
c += x
if t > c:
t = c
if ans < c - t:
ans = c - t
print ans
main()
| 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 | n = int(input())
a = list(map(int, input().split()))
d1 = []
d2 = []
for i in range(n - 1):
if i % 2 == 0:
d1.append(abs(a[i] - a[i + 1]))
d2.append(-1 * abs(a[i] - a[i + 1]))
else:
d1.append(-1 * abs(a[i] - a[i + 1]))
d2.append(abs(a[i] - a[i + 1]))
s1 = [0 for i in range(n)]
s2 = [0 for i in range(n)]
s1[0] = d1[0]
s2[0] = d2[0]
ans = max(s1[0], s2[0])
for i in range(1, n - 1):
s1[i] = max(d1[i], d1[i] + s1[i - 1])
s2[i] = max(d2[i], d2[i] + s2[i - 1])
ans = max(s1[i], s2[i], ans)
# print(s1)
# print(s2)
print(ans) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 2e3 + 5;
const int nmax = 1e5 + 5;
const int mod = 1e9 + 7;
const long double eps = 1e-18;
const long double PI = acos(-1.0);
const long long inf = 1e9;
const long double big = 1e18;
long long d[nmax];
long long s[nmax];
long long a[nmax];
long long ABS(long long first) { return (first < 0 ? -first : first); }
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
s[i - 1] = ABS(a[i] - a[i - 1]);
d[i - 1] = s[i - 1];
if (i % 2)
s[i - 1] = -s[i - 1];
else
d[i - 1] = -d[i - 1];
}
long long ans = max(s[1], d[1]);
long long mns = 0;
long long mnd = 0;
long long ss = 0;
long long sd = 0;
for (int j = 1; j < n; ++j) {
ss += s[j];
sd += d[j];
mns = min(ss, mns);
mnd = min(sd, mnd);
ans = max(ans, ss - mns);
ans = max(ans, sd - mnd);
}
cout << ans << '\n';
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.*;
public class FunctionsAgain{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int a[] = new int [n-1];
int ultimo = sc.nextInt();
for (int i=1;i<n;i++) {
int actual = sc.nextInt();
a[i-1] = Math.abs(ultimo-actual);
ultimo = actual;
}
long max = 0;
long sum = 0;
for (int i=0;i<n-1;i++) {
if (sum<0)
sum=0;
if (i%2==0)
sum += a[i];
else
sum -= a[i];
if (sum>max)
max = sum;
}
sum = 0;
for (int i=0;i<n-1;i++) {
if (sum<0)
sum=0;
if (i%2==1)
sum += a[i];
else
sum -= a[i];
if (sum>max)
max = sum;
}
System.out.println(max);
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n=int(input())
w=[int(k) for k in input().split()]
a=[]
for j in range(1, len(w)):
a.append(abs(w[j]-w[j-1]))
b, c=[], []
for j in range(len(a)):
if j%2:
b.append(-a[j])
c.append(a[j])
else:
b.append(a[j])
c.append(-a[j])
res=0
x, y=[], []
q=0
for j in b:
x.append(q)
q+=j
x.append(q)
q=0
for j in c:
y.append(q)
q+=j
y.append(q)
"""print(b)
print(c)
print(x)
print(y)"""
mx, mn=0, 0
for j in x:
mx=max(mx, j)
mn=min(mn, j)
res=max(res, mx-mn)
mx, mn=0, 0
for j in y:
mx=max(mx, j)
mn=min(mn, j)
res=max(res, mx-mn)
print(res) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.*;
import java.util.*;
import java.lang.Math;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class GFG {
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 main (String[] args) {
FastReader scn=new FastReader();
int n=scn.nextInt();
long m11=0,m12=0,m21=0,m22=0;
long[] a=new long[n];
long[] mod1=new long[n-1];
long[] mod2=new long[n-1];
for(int i=0;i<n;i++){
a[i]=scn.nextInt();
if(i!=0){
mod1[i-1]=Math.abs(a[i-1]-a[i])*((int)Math.pow(-1,i-1));
mod2[i-1]=-mod1[i-1];
if(i==1){
m11=m12=mod1[i-1];
m21=m22=mod2[i-1];
}
else{
m12=Math.max(mod1[i-1],m12+mod1[i-1]);
m11=Math.max(m11,m12);
m22=Math.max(mod2[i-1],m22+mod2[i-1]);
m21=Math.max(m21,m22);
}
}
}
if(m11<m21)
System.out.println(m21);
else
System.out.println(m11);
}
} | 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 int n, a[100005], b[100005], dp[100005];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (long long int i = 1; i <= n; ++i) cin >> a[i];
for (long long int i = 1; i <= n - 1; ++i) b[i] = abs(a[i] - a[i + 1]);
n--;
dp[n] = b[n];
dp[n - 1] = max(b[n - 1], b[n - 1] - b[n]);
long long int ans = max(dp[n], dp[n - 1]);
for (long long int i = n - 2; i >= 1; i--) {
dp[i] = max(b[i], b[i] - b[i + 1] + max(0LL, dp[i + 2]));
ans = max(ans, dp[i]);
}
cout << ans << '\n';
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import math
import sys
n = int(input())
a = []
b = [None] * n
c = [None] * n
for x in input().split():
a.append(int(x))
for i in range(0, n - 1):
b[i] = c[i] = abs(a[i + 1] - a[i])
b[i] *= math.pow(-1, i)
c[i] *= math.pow(-1, i + 1)
maxCurrB = b[0]
maxB = b[0]
maxCurrC = c[0]
maxC = c[0]
for i in range (1, n - 1):
maxCurrB = max(b[i], maxCurrB + b[i])
maxB = max(maxB, maxCurrB)
maxCurrC = max(c[i], maxCurrC + c[i])
maxC = max(maxC, maxCurrC)
print(int(max(maxB, maxC)))
| 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 | R = lambda : map(int, input().split())
n = int(input())
a = list(R())
for i in range(len(a) - 1):
a[i] = abs(a[i] - a[i + 1])
a = [v * (1 if i % 2 == 0 else -1) for i, v in enumerate(a[:-1])]
res = 0
running_sum = 0
for i in range(len(a)):
running_sum += a[i]
res = max(res, abs(running_sum))
if running_sum < 0:
running_sum = 0
running_sum = 0
for i in range(len(a)):
running_sum += a[i]
res = max(res, abs(running_sum))
if running_sum > 0:
running_sum = 0
print(res) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
void __print(int x) { cout << x; }
void __print(long x) { cout << x; }
void __print(long long x) { cout << x; }
void __print(unsigned x) { cout << x; }
void __print(unsigned long x) { cout << x; }
void __print(unsigned long long x) { cout << x; }
void __print(float x) { cout << x; }
void __print(double x) { cout << x; }
void __print(long double x) { cout << x; }
void __print(char x) { cout << '\'' << x << '\''; }
void __print(const char *x) { cout << '\"' << x << '\"'; }
void __print(const string &x) { cout << '\"' << x << '\"'; }
void __print(bool x) { cout << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V> &x) {
cout << '{';
__print(x.first);
cout << ',';
__print(x.second);
cout << '}';
}
template <typename T>
void __print(const T &x) {
int f = 0;
cout << '{';
for (auto &i : x) cout << (f++ ? "," : ""), __print(i);
cout << "}";
}
void _print() { cout << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
__print(t);
if (sizeof...(v)) cout << ", ";
_print(v...);
}
void line(long long x) {
while (x--) {
cout << "-";
}
cout << '\n';
}
template <typename T1, typename T2, typename T3>
void arr_(T1 *a, T2 x, T3 y) {
for (int i = x; i <= y; i++) {
cout << a[i] << " ";
}
cout << '\n';
}
template <typename T>
void queue_(queue<T> x) {
while (!x.empty()) {
T y = x.front();
x.pop();
cout << "["
<< "y"
<< "] = [";
_print(y);
}
line(20);
}
template <typename T>
void stack_(stack<T> x) {
while (!x.empty()) {
T y = x.top();
x.pop();
cout << "["
<< "y"
<< "] = [";
_print(y);
}
line(20);
}
template <typename T>
void pqueue_(priority_queue<T> x) {
while (!x.empty()) {
T y = x.top();
x.pop();
cout << "["
<< "y"
<< "] = [";
_print(y);
}
line(20);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5>
void arr2_(T1 *a, T2 x1, T3 x2, T4 y1, T5 y2) {
for (int i = x1; i <= x2; i++) {
for (int j = y1; j <= y2; j++) {
cout << a[i][j] << " ";
}
cout << '\n';
}
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template <typename T>
T rng2(T a, T b) {
return a + rng() % (b - a + 1);
}
void start() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
srand(time(NULL));
}
template <typename T>
T power(T x, T y) {
if (y == 0) {
return 1;
}
T p = power(x, y / 2);
p = (p * p);
return (y % 2 == 0) ? p : (x * p);
}
template <typename T>
T powm(T x, T y, T m) {
T ans = 1, r = 1;
x %= m;
while (r > 0 && r <= y) {
if (r & y) {
ans *= x;
ans %= m;
}
r <<= 1;
x *= x;
x %= m;
}
return ans;
}
template <typename T>
T gcd(T a, T b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
template <typename T>
T lcm(T a, T b) {
T lar = max(a, b);
T small = min(a, b);
for (T i = lar;; i += lar) {
if (i % small == 0) {
return i;
}
}
}
template <typename T>
T mod(T a, T b) {
return ((a % b) + b) % b;
}
template <typename T>
T mul(T a, T b, T mod) {
return ((a * b) + mod) % mod;
}
template <typename T>
T modmul(T a, T b, T mod) {
T res = 0;
a %= mod;
while (b) {
if (b & 1) res = (res + a) % mod;
a = (2 * a) % mod;
b >>= 1;
}
return res;
}
template <typename T>
T modsum(T a, T b, T mod) {
return (a + b) % mod;
}
bool cmp1(const pair<long long, long long> &a,
const pair<long long, long long> &b) {
return (a.second < b.second);
}
bool cmp2(const pair<long long, long long> &a,
const pair<long long, long long> &b) {
return (a.first > b.first);
}
bool overflow(long double a, long double b) { return a * b > 1e18 + 10; }
const long long N = (long long)(1e5 + 1);
const long long MOD = (long long)(1e9 + 7);
const long long inf = (long long)(1e18);
long long fun(vector<long long> a) {
long long size = (long long)a.size();
long long max_so_far = INT_MIN, max_ending_here = 0;
for (long long i = 0; i < size; i++) {
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here) max_so_far = max_ending_here;
if (max_ending_here < 0) max_ending_here = 0;
}
return max_so_far;
}
void solve(int tc) {
long long n;
cin >> n;
long long prev;
vector<long long> v, v2;
for (long long i = 1; i <= n; i++) {
long long x;
cin >> x;
if (i > 1) {
v.push_back(abs(x - prev) * pow(-1, (i & 1)));
v2.push_back(abs(x - prev) * pow(-1, !(i & 1)));
}
prev = x;
}
cout << max(abs(fun(v)), abs(fun(v2)));
}
int main() {
start();
int t = 1;
for (int tc = 1; tc <= t; tc++) {
for (auto blockTime = make_pair(chrono::high_resolution_clock::now(), true);
blockTime.second;
fprintf(stderr, "%s: %lld ms\n", "solve",
chrono::duration_cast<chrono::milliseconds>(
chrono::high_resolution_clock::now() - blockTime.first)
.count()),
fflush(stderr), blockTime.second = false) {
solve(tc);
}
}
return 0;
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A407 {
public static void main(String[] args) {
FS scan = new FS(System.in);
int N = scan.nextInt();
long[] list = new long[N];
for(int i=0;i<N;i++){list[i] = scan.nextLong();}
long[] diff = new long[N-1], diff2 = new long[N-1];
for(int i=1;i<N;i++)diff[i-1] = Math.abs(list[i]-list[i-1]);
diff2 = Arrays.copyOf(diff, N-1);
for(int i=0;i<N-1;i++){
if((i&1)==0)diff[i]*=-1;
else diff2[i]*=-1;
}
long best = 0;
long cur = 0;
for(int i=0;i<N-1;i++){
cur+=diff[i];
best = (cur>best)?cur:best;
if(cur<0)cur=0;
}
cur = 0;
for(int i=0;i<N-1;i++){
cur+=diff2[i];
best = (cur>best)?cur:best;
if(cur<0)cur=0;
}
System.out.println(best);
}
public static class FS {
BufferedReader br;
StringTokenizer st;
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
public FS(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 100000;
int a[N];
void solve() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n - 1; i++) {
a[i] = abs(a[i] - a[i + 1]);
}
n--;
long long sm = a[0];
long long mx = sm;
for (int i = 1; i < n; i++) {
int x = ((i % 2 == 0) ? a[i] : -a[i]);
sm = max(1LL * x, sm + x);
mx = max(mx, sm);
}
sm = -a[0];
for (int i = 1; i < n; i++) {
int x = ((i % 2 == 1) ? a[i] : -a[i]);
sm = max(1LL * x, sm + x);
mx = max(mx, sm);
}
cout << mx;
}
int main() {
solve();
getchar();
getchar();
}
| 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 FunctionsAgain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[100002];
for(int i = 1 ; i < n+1 ; i++)
arr[i] = scan.nextInt();
int[] dp= new int[100002];
long func_max = 0;
long[] func_arr = new long[100002];
dp[0] = 0;
dp[1] = 1;
func_arr[0] = 0;
for(int i = 2 ; i < n+1; i++) {
long new_input = -Math.abs(arr[i-2]- arr[i-1]) + Math.abs(arr[i-1]-arr[i]) ;
// if( func_arr[i-2]+new_input < 0 ) {
// //dp[i] = i-1;
// func_arr[i] = Math.abs(arr[i-1]-arr[i]);
// }
// else {
// //dp[i] = dp[i-1];
// func_arr[i] = func_arr[i-1] + new_input;
// }
func_arr[i] = Math.max(func_arr[i-2] + new_input, Math.abs(arr[i-1]-arr[i]));
if( func_max < func_arr[i] )
func_max = func_arr[i];
}
System.out.print(func_max);
}
public static int func(int[] arr, int l, int r) {
int result = 0;
for(int i = l ; i < r; i++) {
result += Math.abs(arr[i]-arr[i+1]) * (int)Math.pow(-1, i-l);
}
return result;
}
}
| 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 dat[100005];
long long s[100005];
int main() {
int n;
scanf("%d", &n);
long long ans = LLONG_MIN;
for (int i = 1; i <= n; i++) {
scanf("%d", &dat[i]);
s[i] = abs(dat[i] - dat[i - 1]);
}
s[1] = 0;
long long now = 0;
for (int i = 2; i <= n; i += 2) {
now = max(now + s[i] - s[i - 1], s[i]);
ans = max(ans, now);
}
now = 0;
for (int i = 3; i <= n; i += 2) {
now = max(now + s[i] - s[i - 1], s[i]);
ans = max(ans, now);
}
printf("%lld\n", ans);
}
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<long long> v(n), b(n - 1), c(n - 2);
for (int i = 0; i < n; i++) cin >> v[i];
b[0] = abs(v[1] - v[0]);
if (n == 2) {
cout << b[0];
return 0;
}
for (int i = 2; i < n; i++) {
if (i % 2)
b[i - 1] = abs(v[i] - v[i - 1]);
else
b[i - 1] = -abs(v[i] - v[i - 1]);
}
c[0] = abs(v[2] - v[1]);
for (int i = 3; i < n; i++) {
if (i % 2 == 0)
c[i - 2] = abs(v[i] - v[i - 1]);
else
c[i - 2] = -abs(v[i] - v[i - 1]);
}
long long tmp = 0, hi = 0;
for (int i = 0; i < n - 1; i++) {
tmp += b[i];
hi = max(hi, tmp);
if (tmp < 0) tmp = 0;
}
hi = max(hi, tmp);
tmp = 0;
for (int i = 0; i < n - 2; i++) {
tmp += c[i];
hi = max(hi, tmp);
if (tmp < 0) tmp = 0;
}
hi = max(hi, tmp);
cout << hi;
}
| 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 | /**************************************************\
| | |-----------| |-----------||
| | | | |
| | | | |
|------------| |------| | |
| | | | |
| | | | |
| | |-----------| | |
|
DA-IICT, Gandhinagar |
**************************************************/
import java.io.*;
import java.util.*;
public class Main{
public static final int MOD = (int) (1e9 + 7);
public static InputReader in;
public static PrintWriter w;
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
try{
//double startTime=System.currentTimeMillis();
solve();
w.flush();
//w.println((System.currentTimeMillis()-startTime)/1000.0);
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
static int tree[],a[];
static void solve() throws FileNotFoundException{
in = new InputReader(System.in);
//w = new PrintWriter(new File("E:/inA.in"));
w = new PrintWriter(System.out);
int n=in.nextInt();
int arr[]=in.nextIntArray(n);
int a1[]=new int[n-1];
int a2[]=new int[n-1];
for(int i=0;i<n-1;i++){
int val=Math.abs(arr[i]-arr[i+1]);
if(i%2==0){
a1[i]=val;
a2[i]=-a1[i];
}else{
a2[i]=val;
a1[i]=-a2[i];
}
}
int size = a1.length;
long max_so_far = Long.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a1[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0){
max_ending_here = 0;
if((i+1)%2!=0)
i++;
}
}
long max=max_so_far;
size = a2.length;
max_so_far = Long.MIN_VALUE;
max_ending_here = 0;
for (int i = 1; i < size; i++)
{
max_ending_here = max_ending_here + a2[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0){
max_ending_here = 0;
if((i+1)%2==0)
i++;
}
}
max=Math.max(max, max_so_far);
w.println(max);
}
static int maxSubArraySum(int a[])
{
int size = a.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.util.Scanner;
public class functionAgain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
long n=sc.nextLong();
long a=sc.nextLong();
long sum=0,max=0,min=0;
for(int i=1;i<n;i++)
{
long b=sc.nextLong();
if(i%2==0)
{
sum+=Math.abs(a-b)*-1;
}
else
{
sum+=Math.abs(a-b);
}
max=Math.max(max,sum);
min=Math.min(sum,min);
a=b;
}
System.out.println(max-min);
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long a[1000001];
int main() {
long long n, k;
cin >> n >> k;
long long count = 0;
for (long long i = 0; i < n - 1; i++) {
long long x;
cin >> x;
count += (pow(-1, i) * (abs(k - x)));
a[i] = count;
k = x;
}
sort(a, a + n - 1);
if (a[0] >= 0)
cout << a[n - 2];
else
cout << a[n - 2] - a[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 | from sys import stdin, stdout
n = int(stdin.readline())
values = list(map(int, stdin.readline().split()))
first = []
second = []
ans = float('-inf')
for i in range(n - 1):
first.append(abs(values[i] - values[i + 1]) * (-1) ** i)
second.append(abs(values[i] - values[i + 1]) * (-1) ** (i + 1))
cnt = 0
for i in range(n - 1):
cnt += first[i]
ans = max(ans, cnt)
if cnt < 0:
cnt = 0
cnt = 0
for i in range(n - 1):
cnt += second[i]
ans = max(ans, cnt)
if cnt < 0:
cnt = 0
stdout.write(str(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 | R=lambda:list(map(int,input().split()))
n=int(input())
a=R()
dif=[0]*(n-1)
for i in range(n-1):
dif[i]=abs(a[i]-a[i+1])*(1-2*(i%2))
sum=[0]*(n)
sum[0]=0
for i in range(1,n):
sum[i]=sum[i-1]+dif[i-1]
ma=[0]*(n-1)
mi=[0]*(n-1)
for i in range(n-2,-1,-1):
ma[i]=max(sum[i+1],ma[i+1] if i<n-2 else sum[i+1])
mi[i]=min(sum[i+1],mi[i+1] if i<n-2 else sum[i+1])
res=0
for i in range(n-1):
if i%2==0:
res=max(res,ma[i]-sum[i])
else:
res=max(res,-(mi[i]-sum[i]))
print(res) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(input())
a = [int(i) for i in input().split()]
b = [abs(a[i] - a[i - 1]) for i in range(1, len(a))]
sm = [[0] * 2 for i in range(n)]
mn = [[0] * 2 for i in range(n + 1)]
ans = -1000000
for i in range(n - 2, -1, -1):
if i % 2 == 0:
sm[i][0] = b[i] + sm[i + 1][0]
sm[i][1] = -b[i] + sm[i + 1][1]
mn[i][1] = min(mn[i + 2][1], sm[i][1])
ans = max(ans, sm[i][0] - mn[i + 1][0])
else:
sm[i][1] = b[i] + sm[i + 1][1]
sm[i][0] = -b[i] + sm[i + 1][0]
mn[i][0] = min(mn[i + 2][0], sm[i][0])
ans = max(ans, sm[i][1] - mn[i + 1][1])
print(ans) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(input())
l = list(map(int,input().split()))
M = abs(l[0]-l[1])
k = 0
i = 0
t_p = 0
t_n = 0
while ( i < n-1 ) :
k = ( abs(l[i]-l[i+1]),-abs(l[i]-l[i+1]) )[i%2]
t_n += k
t_p -= k
M = max(M,t_n,t_p)
t_p = max(0,t_p)
t_n = max(0,t_n)
i += 1
print(M)
| PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 7;
const long long inf = 1e18 + 7;
const long long mod = 1e9 + 7;
int n;
int a[N];
long long mn;
long long mn1;
long long sum;
long long sum1;
long long b[N];
long long c[N];
int main() {
ios_base::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i < n; i++) {
b[i] += b[i - 1] + abs(a[i] - a[i + 1]) * (i % 2 ? -1 : 1);
c[i] += c[i - 1] + abs(a[i] - a[i + 1]) * (i % 2 ? 1 : -1);
sum = max(sum, b[i] - mn);
sum1 = max(sum1, c[i] - mn1);
mn = min(mn, b[i]);
mn1 = min(mn1, c[i]);
}
cout << max(sum, sum1);
}
| 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[200001];
long long b[200001];
int main() {
int n, i, k, j;
cin >> n;
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < n - 1; i++) {
b[i] = abs(a[i + 1] - a[i]);
}
long long f = -1;
long long ans1 = b[0], ans2 = b[1], ma1 = b[0], ma2 = b[1];
for (i = 1; i < n - 1; i++) {
ans1 = ans1 + f * b[i];
f = f * (long long)(-1);
if (ans1 > ma1) ma1 = ans1;
if (ans1 < 0) ans1 = 0;
}
f = (long long)(-1);
for (i = 2; i < n - 1; i++) {
ans2 = ans2 + f * b[i];
f = f * (long long)(-1);
if (ans2 > ma2) ma2 = ans2;
if (ans2 < 0) ans2 = 0;
}
cout << max(ma1, ma2);
}
| 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 = []
sign = 1
for i in range(len(a)-1):
b.append( abs(a[i]-a[i+1]) * sign )
sign *= -1
max_ = 0
max1, max2 = 0, 0
a1, a2 = 0, 0
for i in range(n-1):
if a1+b[i]>0:
a1 += b[i]
else:
a1 = 0
max1 = max(a1, max1)
if a2-b[i]>0:
a2 -= b[i]
else:
a2 = 0
max2 = max(a2, max2)
print(max(max1,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 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int n, curr, posFor, negFor, temp, *arr;
long long int maxp, maxn;
cin >> n;
arr = new long long int[n];
for (long int i = 0; i < n; i++) {
cin >> temp;
arr[i] = temp;
}
maxp = maxn = LONG_MIN;
negFor = 0;
posFor = 0;
for (long int i = n - 2; i >= 0; i--) {
curr = abs(arr[i] - arr[i + 1]);
if ((i + 1) % 2 == 1) {
if (negFor - curr < 0)
negFor = 0;
else
negFor -= curr;
posFor += curr;
maxp = max(maxp, posFor);
} else {
if (posFor - curr < 0)
posFor = 0;
else
posFor -= curr;
negFor += curr;
maxn = max(maxn, negFor);
}
}
cout << max(maxp, maxn) << endl;
delete[] arr;
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 | """
Code of Ayush Tiwari
Codeforces: servermonk
Codechef: ayush572000
"""
import sys
input = sys.stdin.buffer.readline
def solution():
n=int(input())
l=list(map(int,input().split()))
d=[0]*(n+1)
for i in range(n-1):
if i%2==0:
d[i+1]=d[i]+abs(l[i]-l[i+1])
else:
d[i+1]=d[i]-abs(l[i]-l[i+1])
d.sort()
# print(d)
print(d[n]-d[0])
solution() | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
long long dp[2][N];
int main() {
int T;
int n;
cin >> n;
vector<long long> a(n + 1);
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
}
long long res = 0;
for (int i = 1; i < n; ++i) {
long long tmp = abs(a[i + 1] - a[i]);
dp[1][i] = dp[0][i - 1] + tmp;
dp[0][i] = max(0ll, dp[1][i - 1] - tmp);
res = max(res, max(dp[1][i], dp[0][i]));
}
printf("%lld\n", 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 sys
import os
import time
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random
from io import BytesIO, IOBase
from bisect import bisect_left as bl
from bisect import bisect_right as br
#########################
# imgur.com/Pkt7iIf.png #
#########################
# returns the list of prime numbers less than or equal to n:
'''def sieve(n):
if n < 2: return list()
prime = [True for _ in range(n + 1)]
p = 3
while p * p <= n:
if prime[p]:
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 2
r = [2]
for p in range(3, n + 1, 2):
if prime[p]:
r.append(p)
return r'''
# returns all the divisors of a number n(takes an additional parameter start):
'''def divs(n, start=1):
divisors = []
for i in range(start, int(math.sqrt(n) + 1)):
if n % i == 0:
if n / i == i:
divisors.append(i)
else:
divisors.extend([i, n // i])
return divisors'''
# returns the number of factors of a given number if a primes list is given:
'''def divn(n, primes):
divs_number = 1
for i in primes:
if n == 1:
return divs_number
t = 1
while n % i == 0:
t += 1
n //= i
divs_number *= t
return divs_number'''
# returns the leftmost and rightmost positions of x in a given list d(if x isnot present then returns (-1,-1)):
'''def flin(d, x, default=-1):
left = right = -1
for i in range(len(d)):
if d[i] == x:
if left == -1: left = i
right = i
if left == -1:
return (default, default)
else:
return (left, right)'''
# returns (b**p)%m
'''def modpow(b,p,m):
res=1
b=b%m
while(p):
if p&1:
res=(res*b)%m
b=(b*b)%m
p>>=1
return res'''
# if m is a prime this can be used to determine (1//a)%m or modular multiplicative inverse of a number a
'''def mod_inv(a,m):
return modpow(a,m-2,m)'''
# returns the ncr%m for (if m is a prime number) for very large n and r
'''def ncr(n,r,m):
res=1
if r==0:
return 1
if n-r<r:
r=n-r
p,k=1,1
while(r):
res=((res%m)*(((n%m)*mod_inv(r,m))%m))%m
n-=1
r-=1
return res'''
# returns ncr%m (if m is a prime number and there should be a list fact which stores the factorial values upto n):
'''def ncrlis(n,r,m,fact):
return (fact[n]*(mod_inv(fact[r],m)*mod_inv(fact[n-r],m))%m)%m'''
def ceil(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def prr(a, sep=' '): print(sep.join(map(str, a)))
def dd(): return collections.defaultdict(int)
def ddl(): return collections.defaultdict(list)
def ddd(): return collections.defaultdict(collections.defaultdict(int))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n=ii()
a=li()
if n==2:
print(abs(a[0]-a[1]))
exit()
mx_cur1,mx_glob1=abs(a[0]-a[1]),abs(a[0]-a[1])
for i in range(1,n-1):
tmp=abs(a[i]-a[i+1])*(-1)**i
mx_cur1=max(mx_cur1+tmp,tmp)
mx_glob1=max(mx_cur1,mx_glob1)
mx_cur2,mx_glob2=abs(a[1]-a[2]),abs(a[1]-a[2])
for i in range(2,n-1):
tmp=abs(a[i]-a[i+1])*(-1)**(i-1)
mx_cur2=max(mx_cur2+tmp,tmp)
mx_glob2=max(mx_glob2,mx_cur2)
print(max(mx_glob1,mx_glob2)) | PYTHON3 |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class FunctionsAgain {
InputStream is;
PrintWriter pw;
String INPUT = "";
long L_INF = (1L << 60L);
void solve() {
int n = ni(), m;
int a[] = na(n);
int diff[] = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
diff[i] = Math.abs(a[i] - a[i + 1]);
}
int b[] = new int[n - 1];
int c[] = new int[n - 1];
long currSum = 0, max1 = 0;
for (int i = 0; i < n - 1; i++) {
b[i] = diff[i] * ((i & 1) == 1 ? -1 : 1);
c[i] = diff[i] * ((i & 1) == 1 ? 1 : -1);
}
max1 = b[0];
int bOrigStart = 0, bEnd, bStart;
for (int i = 0; i < n - 1; i++) {
if ((currSum + b[i]) > b[i]) {
currSum += b[i];
} else {
currSum = b[i];
bOrigStart = i;
}
if (max1 < currSum) {
max1 = currSum;
bStart = bOrigStart;
bEnd = i;
}
}
currSum=0;
long cOrigStart = 0, cEnd, cStart, max2 = c[0];
for (int i = 0; i < n - 1; i++) {
if ((currSum + c[i]) > c[i]) {
currSum += c[i];
} else {
currSum = c[i];
cOrigStart = i;
}
if (max2 < currSum) {
max2 = currSum;
cStart = cOrigStart;
cEnd = i;
}
}
pw.println(Math.max(max1, max2));
}
void run() throws Exception {
// is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
is = System.in;
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
// int t = ni();
// while (t-- > 0)
solve();
pw.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new FunctionsAgain().run();
}
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
}
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 |
import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.lang.Object;
public class Main {
static class sort implements Comparator<int[]>
{
public int compare(int[] a,int[] b)
{
if(a[1] == b[1]) return -b[0]+a[0];
return a[1]-b[1];
}
}
static class sort2 implements Comparator<long[]>
{
public int compare(long[] a,long[] b)
{
//if(a[0] == b[0]) return a[1]-b[1];
/*if(a[1] < b[1]) return -1;
else if(a[1] > b[1]) return 1;
return a[0]-b[0];*/
return (int)(a[0]-b[0]);
}
}
static class sort1 implements Comparator<double[]>
{
public int compare(double[] a,double[] b)
{
//if(a[0] == b[0]) return a[1]-b[1];
if(a[1] < b[1]) return -1;
else if(a[1] > b[1]) return 1;
return 0;
}
}
public static String[] F(BufferedReader bf) throws Exception
{
return (bf.readLine().split(" "));
}
public static void pr(PrintWriter out,Object o)
{
out.println(o.toString());//out.flush();
}
public static void prW(PrintWriter out,Object o)
{
out.print(o.toString());//out.flush();
}
public static int intIn(String st)
{
return Integer.parseInt(st);
}
public static void pr(Object o)
{
System.out.println(o.toString());
}
public static void prW(Object o)
{
System.out.print(o.toString());
}
public static int inInt(String s)
{
return Integer.parseInt(s);
}
public static long in(String s)
{
return Long.parseLong(s);
}
static int[] toIntArray(String[] m)
{
int[] p=new int[m.length];
for(int o=0;o<m.length;o++)
{
p[o]= inInt(m[o]);
}
return p;
}
static double[] toDArray(String[] m)
{
double[] p=new double[m.length];
for(int o=0;o<m.length;o++)
{
p[o]= Double.parseDouble(m[o]);
}
return p;
}
static long[] toLArray(String[] m)
{
long[] p=new long[m.length];
for(int o=0;o<m.length;o++)
{
p[o]= in(m[o]);
}
return p;
}
static int[][] di={{0,1},{1,0},{0,-1},{-1,0}};
static int[] dir = {4,3,2,-4,-3,-2};
public static void F(int i,int c,int[] vis,List<Integer> res,int n)
{
vis[i]=1;
res.add(i);
for(int x : dir)
{
int v = i+x;
if(v<=0 || v>n) continue;
if(vis[v] == 0)
{
F(v,c,vis,res,n);
}
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long Gp(long l,long b,long lcm)
{
long c1,c2;
c1 = (l/lcm);
long sum=0l;
sum += (c1-1l)*(b);
long las = (l/lcm)*lcm;
sum += Math.min(l-las+1l,b);
return sum;
}
static long pow(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0l; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
public static boolean ok(int mid,int[] arr,int[][] mat,int q)
{
int tot=0;
for(int[] a : mat)
{
int p=a[0];
int l = a[1];
int ans=q+1;
int g = Math.abs(p);
if(p==0) continue;
for(int o=0;o<arr.length;o++)
{
if((arr[o]*p) < 0)
{
int sp = Math.abs(arr[o]);
int v = (g/sp);
if((g%sp) != 0) v++;
if(v<=mid)
{
ans=Math.min(ans,Math.abs(l-o));
}
}
}
if(ans > q ) return false;
tot += ans;
}
return tot<=q;
}
public static long F(int a,int b)
{
return 462161773423l*(a+0l) + 4549834777463l*(b+0l);
}
public static void update(int[] diff,int i,long k)
{
int j=(int)(k);
if(j<i) return;
diff[i] +=1;
diff[j+1] -=1;
}
public static long F(int o)
{
long ans=1l;
long g = 1l;
while(o>0)
{
if((o%2) != 0)
{
ans = (ans * g);
}
g++;
o=(o>>1);
}
return ans;
}
public static long F(int x,int y,Long[][] dp)
{
pr(y);
if(y<=0)
{
return 0l;
}
if((10-x) > y)
{
dp[x][y] = 1l;return 1l;
}
if((10-x) == y)
{
dp[x][y] = 2l;return 2l;
}
if(dp[x][y] != null) return dp[x][y];
long val = F(1,y-(10-x),dp) + F(0,y-(10-x),dp);
dp[x][y] = val;return val;
}
static TreeSet<Long> Fu(long n)
{
// Note that this loop runs till square root
TreeSet<Long> list = new TreeSet<>();
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
list.add(i+0l);
else {
list.add(i+0l);
list.add(n/i);
}
}
}
return list;
}
public static int F(int x,List<List<Integer>> list,int[] over,int u)
{
over[x]=1;
int bol = 0;
for(int y : list.get(x))
{
if(y==u) continue;
//if(y != u)
{
if(over[y] == 1)
{
bol=1;
}
else
{
if((F(y,list,over,x)) == 1) bol=1;
}
}
}
return bol;
}
public static long F(int i,int j,Long[][] mat,long[] a,long[] c)
{
if(i == j)
{
mat[i][j]=a[i]*c[j];
return a[i]*c[j];
}
if(i>j) return 0l;
long val = F(i+1,j-1,mat,a,c) + (a[i]*c[j])+(a[j]*c[i]);
mat[i][j]=val;return val;
}
public static void main (String[] args) throws Exception {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);;;
//int[] map=new int[1000001];
int yy=1;//inInt(bf.readLine());
for(int w=0;w<yy;w++)
{
// String str = bf.readLine();
out.flush();
String[] xlp = bf.readLine().split(" ");;;;;;
//String st = bf.readLine();
int n,t;//boolean bol=false;
int m;//long a,b,c;
int ioo;
int k;//pr(out,"vbc");
n=inInt(xlp[0]);//m=inInt(xlp[1]);k=inInt(xlp[2]);//t=inInt(xlp[3]);
// k=inInt(xlp[1]);
long[] arr = toLArray(F(bf));
long[] tem = new long[n-1];
for(int o=0;o<n-1;o++)
{
tem[o] = Math.abs(arr[o]-arr[o+1]);
}
long min1,min;min1=min=0l;
long p,q;p=q=0l;long res=0l;
for(int o=0;o<n-1;o++)
{
if((o%2) == 0) p+=tem[o];
else q+=tem[o];
res=Math.max(res,(p-q)-(min));
res=Math.max(res,(q-p)-min1);
min=Math.min(min,p-q);
min1= Math.min(min1,q-p);
}
pr(out,res);
}
out.close();
bf.close();
}}
/*
8
0
2
51
63
69
75
80
90
100663319,201326611,402653189,805306457,1610612741
Kickstart
String rp;
rp = "Case #"+(w+1)+": "+(n-ans)+" ";
static int[][] dir={{0,1},{1,0},{-1,0},{0,-1}};
static class SegmentTreeRMQ
{
int st[];
int minVal(int x, int y) {
return (x > y) ? x : y;
}
int getMid(int s, int e) {
return s + (e - s) / 2;
}
int RMQUtil(int ss, int se, int qs, int qe, int index)
{
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the given range
if (se < qs || ss > qe)
return Integer.MIN_VALUE;
// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1),
RMQUtil(mid + 1, se, qs, qe, 2 * index + 2));
}
// Return minimum of elements in range from index qs (query
// start) to qe (query end). It mainly uses RMQUtil()
int RMQ(int n, int qs, int qe)
{
// Check for erroneous input values
return RMQUtil(0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for
// array[ss..se]. si is index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se, int si)
{
// If there is one element in array, store it in current
// node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then recur for left and
// right subtrees and store the minimum of two values in this node
int mid = getMid(ss, se);
st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1),
constructSTUtil(arr, mid + 1, se, si * 2 + 2));
return st[si];
}
void con(int arr[])
{
// Allocate memory for segment tree
//Height of segment tree
int n = (arr.length);
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
//Maximum size of segment tree
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // allocate memory
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, 0);
}
}
static class DSU {
int[] p;int[] sz;int op;int c;;
int[] last;
public void G(int n)
{
last=new int[n];
p=new int[n];
sz=new int[n];c=n;
op=n;
for(int h=0;h<n;h++)
{
sz[h]=1;p[h]=h;
last[h]=h;
}
}
public int find(int x)
{
int y=x;
while(x!=p[x]) x=p[x];
while(y!=p[y])
{
int tem=p[y];
p[y]=x;y=tem;
}
return p[y];
}
public void union(int a,int b)
{
int x,y;
x=find(a);y=find(b);
if(x==y) return;
if(sz[x]>sz[y])
{
p[y] = x;
sz[x]+=sz[y];
last[x]=Math.max(last[x],last[y]);
}
else
{
p[x]=y;sz[y]+=sz[x];
last[y]=Math.max(last[y],last[x]);
}
c--;
}}
static long pow(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0l; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static int gcd(int a, int b,int o)
{
if (b == 0)
return a;
return gcd(b, a % b,o);
}
Geometric median
public static double F(double[] x,double[] w)
{
double d1,d2;
double S=0.00;
for(double dp : w) S += dp;
int k = 0;
double sum = S - w[0]; // sum is the total weight of all `x[i] > x[k]`
while(sum > S/2)
{
++k;
sum -= w[k];
}
d1=x[k];
return d1;
k = w.length-1;
sum = S - w[k]; // sum is the total weight of all `x[i] > x[k]`
while(sum > S/2)
{
--k;
sum -= w[k];
}
d2=x[k];
return new double[]{d1,d2};
}
*/
| JAVA |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | n = int(input())
arr = list(map(int, input().strip().split()))
arr1 = [(1-2*(i%2))*abs(arr[i]-arr[i+1]) for i in range(n-1)]
arr2 = [(1-2*(1-i%2))*abs(arr[i]-arr[i+1]) for i in range(n-1)]
so_far = 0
sumi = 0
# print(arr1)
# print(arr2)
for i in arr1:
sumi += i
if sumi < 0:
sumi = 0
else:
so_far = max(sumi, so_far)
sumi = 0
for i in arr2:
sumi += i
if sumi < 0:
sumi = 0
else:
so_far = max(sumi, so_far)
# so_far = max(sumi, so_far)
print(so_far)
| 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() {
int n;
cin >> n;
vector<long long> a(n);
for (auto &it : a) cin >> it;
;
long long dp[n + 5][5];
memset(dp, 0, sizeof(dp));
dp[0][1] = abs(a[0] - a[1]);
long long ans = dp[0][1];
for (int i = 1; i < n - 1; i++) {
dp[i][1] = max(dp[i - 1][0] + abs(a[i] - a[i + 1]), abs(a[i] - a[i + 1]));
dp[i][0] = dp[i - 1][1] - abs(a[i] - a[i + 1]);
ans = max({ans, dp[i][1], dp[i][0]});
}
cout << ans << '\n';
}
int main() { solve(); }
| CPP |
788_A. Functions again | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n;
cin >> n;
long long arr[n];
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
vector<long long> a, b;
for (int i = 0; i < n - 1; i++) {
if (i % 2) {
a.push_back(-abs(arr[i] - arr[i + 1]));
b.push_back(abs(arr[i] - arr[i + 1]));
} else {
a.push_back(abs(arr[i] - arr[i + 1]));
b.push_back(-abs(arr[i] - arr[i + 1]));
}
}
long long max1 = a[0], max2 = b[0], curmax1 = a[0], curmax2 = b[0];
for (int i = 1; i < a.size(); i++) {
curmax1 = max(a[i], curmax1 + a[i]);
max1 = max(max1, curmax1);
curmax2 = max(b[i], curmax2 + b[i]);
max2 = max(max2, curmax2);
}
cout << max(max1, max2);
}
| CPP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.