The Strange Function
Problem Statement :
One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting of n integers [ a1, a2, . . . , an ] . Input Format The first line contains a single integer n The second line contains n space-separated integers a1, a2, . . . , an . Constraints 1 <= n <= 50000 - 10^6 <= ai <= 10^6 Output Format Print a single integer denoting the answer
Solution :
Solution in C :
In C ++ :
#define _CRT_SECURE_NO_WARNINGS
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#include <assert.h>
#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash
#define norm asdfasdgasdgsd
#define have adsgagshdshfhds
#define ends asdgahhfdsfshdshfd
#define eps 1e-8
#define M_PI 3.141592653589793
#define bsize 512
#define ldouble long double
using namespace std;
#define bs 1000000007
const int N = 600031;
int n,ar[N];
long long S[N];
long long sparse_gcd[20][N],sparse_s[20][N],sparse_max[20][N];
int gcd(int a,int b){
b=abs(b);
while (a&&b)a>b?a%=b:b%=a;
return a+b;
}
vector<pair<long long, long long> > order;
long long suf_max[N];
int main(){
// freopen("apache.in","r",stdin);
// freopen("apache.out","w",stdout);
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
ios_base::sync_with_stdio(0);
// cin.tie(0);
cin>>n;
long long ttl=0;
for (int i=1;i<=n;i++){
cin>>ar[i];
S[i]=S[i-1]+ar[i];
}
suf_max[n]=S[n];
for (int i=n-1;i>=0;--i)
suf_max[i]=max(suf_max[i+1],S[i]);
long long ans=-1e18;
order.clear();
for (int i=1;i<=n;i++){
order.push_back(make_pair(S[i],i));
}
sort(order.begin(),order.end());
long long MX=order.back().first;
srand(time(NULL));
if (rand()%2)
random_shuffle(order.begin(),order.end());
for (int ii=0;ii<order.size();ii++){
int i=order[ii].second;
ttl=MX-order[ii].first;
long long cur_gcd=0;
int cur_max=-1e9;
long long cur_s=0;
for (int j=i;j<=n;j++){
cur_gcd=gcd(cur_gcd,ar[j]);
cur_max=max(cur_max,ar[j]);
cur_s+=ar[j];
long long here=cur_gcd*(cur_s-cur_max);
if (cur_gcd*1ll*(suf_max[j]-order[ii].first)<=ans)
break;
if (here>ans)
ans=here;
}
if (clock()*1.0/CLOCKS_PER_SEC>1.98)
break;
}
cout<<ans<<endl;
cin.get(); cin.get();
return 0;
}
In Java :
//package hackerrank;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
import java.util.TreeMap;
public class Solution98 {
static final Scanner scanner = new Scanner(System.in);
static class Segment {
int left, right, val;
Segment(int left, int right, int val) {
this.left = left;
this.right = right;
this.val = val;
}
}
private static int gcd(int x, int y) {
if (y == 0) {
return x;
}
return gcd(y, x % y);
}
public static void main(String[] args) {
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
long ans = 0;
long sum = 0;
TreeMap<Integer, Integer> tmap = new TreeMap<>();
SegmentTree tree = new SegmentTree(n);
Deque<Segment> dq = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
TreeMap<Integer, Integer> segmentTree = new TreeMap<>();
for (int j : tmap.keySet()) {
int k = gcd(j, Math.abs(a[i]));
int idx = tmap.get(j);
if (segmentTree.containsKey(k)) {
int cur = segmentTree.get(k);
segmentTree.put(k, Math.min(idx, cur));
} else {
segmentTree.put(k, idx);
}
}
if (segmentTree.containsKey(Math.abs(a[i]))) {
int j = segmentTree.get(Math.abs(a[i]));
segmentTree.put(Math.abs(a[i]), Math.min(i, j));
} else {
segmentTree.put(Math.abs(a[i]), i);
}
tmap = segmentTree;
tree.add(i, i, sum);
Segment s = new Segment(i, i, a[i]);
while (!dq.isEmpty() && dq.getLast().val <= a[i]) {
tree.add(dq.getLast().left, dq.getLast().right, -dq.getLast().val);
s.left = dq.getLast().left;
dq.removeLast();
}
tree.add(s.left, s.right, s.val);
dq.addLast(s);
sum += a[i];
for (int j : tmap.keySet()) {
int pos = tmap.get(j);
ans = Math.max(ans, j * (sum - tree.get(pos, i)));
}
}
System.out.println(ans);
}
}
class SegmentTree {
private int n;
private long[] min, add;
SegmentTree(int size) {
n = 1;
while (n < size) {
n *= 2;
}
min = new long[2 * n];
add = new long[2 * n];
}
private void clear(int i, int l, int r) {
min[i] = 0;
add[i] = 0;
if (l == r - 1) {
return;
}
int tm = (l + r) / 2;
clear(2 * i + 1, l, tm);
clear(2 * i + 2, tm, r);
}
void clear(int n) {
this.n = n;
clear(0, 0, n);
}
private void push(int i, int tl, int tr) {
min[i] += add[i];
if (tl != tr - 1) {
add[2 * i + 1] += add[i];
add[2 * i + 2] += add[i];
}
add[i] = 0;
}
private void add(int i, int lt, int rt, int l, int r, long diff) {
push(i, lt, rt);
if (l >= rt || r <= lt) {
return;
}
if (l <= lt && rt <= r) {
add[i] += diff;
push(i, lt, rt);
return;
}
int tm = (lt + rt) / 2;
add(2 * i + 1, lt, tm, l, r, diff);
add(2 * i + 2, tm, rt, l, r, diff);
min[i] = Math.min(min[2 * i + 1], min[2 * i + 2]);
}
private long get(int i, int lt, int rt, int l, int r) {
push(i, lt, rt);
if (l >= rt || r <= lt) {
return Long.MAX_VALUE;
}
if (l <= lt && rt <= r) {
return min[i];
}
int tm = (lt + rt) / 2;
return Math.min(get(2 * i + 1, lt, tm, l, r), get(2 * i + 2, tm, rt, l, r));
}
void add(int l, int r, long diff) {
add(0, 0, n, l, r + 1, diff);
}
long get(int l, int r) {
return get(0, 0, n, l, r + 1);
}
}
In C :
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define INF 200000
typedef struct _node{
int gcd;
int max;
long long sum;
} node;
typedef struct _tree_node{
enum {red,black} colour;
int data;
int real;
struct _tree_node *left,*right,*parent;
}tree_node;
void solve(int start,int bs,int ns);
void copy_tree(tree_node **d,tree_node *r);
void build(int v,int tl,int tr);
long long query(int v,int tl,int tr,int l,int r,int *gcd,int *ma,long long *sum);
void getp(long long N,long long*prim);
long long CC(long long n, long long d);
int max(int x,int y);
int min(int x,int y);
int abss(int x);
int search(tree_node *root,int data);
void left_rotate(tree_node **root,tree_node *x);
void right_rotate(tree_node **root,tree_node *y);
void reconstruct(tree_node **root,tree_node *x);
int normal_insert(tree_node **root,tree_node *x);
void insert(tree_node **root,tree_node *x);
void sort_a(int*a,int size,int*new_size);
void merge(int*a,int*left,int*right,int left_size, int right_size,int*new_size);
void init( int n );
int range_sum( int i, int j );
void update( int i, long long val );
int a[50000],b[50000],nonzero[50000],rp[30],rc[30],treei[200000],rs,s,N;
long long ans,p[1000],tree[200000];
node t[200000];
tree_node *map[50000];
int main(){
int n,x,ns,i,j,k,l;
long long sum;
tree_node *last_node,*p_node;
getp(1000,p);
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",a+i);
build(1,0,n-1);
init(n);
for(i=sum=0;i<n;i++){
sum+=a[i];
update(i,sum);
}
for(i=n-1;i>=0;i--){
if(i==n-1)
last_node=NULL;
else
last_node=map[i+1];
if(a[i]){
nonzero[i]=i;
for(j=rs=0,x=abss(a[i]);p[j] && p[j]*p[j]<=x;j++)
if(x%p[j]==0){
rp[rs]=p[j];
rc[rs]=0;
while(x%p[j]==0){
rc[rs]++;
x/=p[j];
}
rs++;
}
if(x!=1){
rp[rs]=x;
rc[rs]=1;
rs++;
}
for(j=s=0;j<rs;j++)
for(k=0,x=rp[j];k<rc[j];k++,x*=rp[j]){
p_node=(tree_node*)malloc(sizeof(tree_node));
p_node->data=x;
p_node->left=p_node->right=p_node->parent=NULL;
l=search(last_node,x);
if(l!=INF){
p_node->real=l;
b[s++]=l+1;
}
else
p_node->real=i;
insert(&map[i],p_node);
}
b[s++]=i;
sort_a(b,s,&ns);
solve(i,ns,n);
}
else{
nonzero[i]=INF;
s=0;
copy_tree(&map[i],last_node);
if(i!=n-1 && nonzero[i+1]!=INF)
b[s++]=nonzero[i+1];
sort_a(b,s,&ns);
solve(i,ns,n);
}
if(i!=n-1)
nonzero[i]=min(nonzero[i],nonzero[i+1]);
}
printf("%lld",ans);
return 0;
}
void solve(int start,int bs,int ns){
int gcd,ma,i,j;
long long t,sum;
for(i=0;i<bs;i++){
if(b[i]==ns)
continue;
if(i==bs-1)
j=range_sum(b[i],ns-1);
else
j=range_sum(b[i],b[i+1]-1);
t=query(1,0,ns-1,start,j,&gcd,&ma,&sum);
if(t>ans)
ans=t;
}
return;
}
void copy_tree(tree_node **d,tree_node *r){
tree_node *p;
if(!r)
return;
copy_tree(d,r->left);
p=(tree_node*)malloc(sizeof(tree_node));
p->data=r->data;
p->real=r->real;
p->left=p->right=p->parent=NULL;
insert(d,p);
b[s++]=r->real+1;
copy_tree(d,r->right);
return;
}
void build(int v,int tl,int tr){
int tm;
if(tl==tr){
t[v].gcd=abss(a[tl]);
t[v].max=t[v].sum=a[tl];
}
else{
tm=(tl+tr)/2;
build(2*v,tl,tm);
build(2*v+1,tm+1,tr);
t[v].gcd=CC(t[2*v].gcd,t[2*v+1].gcd);
t[v].max=max(t[2*v].max,t[2*v+1].max);
t[v].sum=t[2*v].sum+t[2*v+1].sum;
}
return;
}
long long query(int v,int tl,int tr,int l,int r,int *gcd,int *ma,long long *sum){
int tm,g1,g2,m1,m2;
long long s1,s2;
if(tl>r || tr<l){
*gcd=0;
*ma=0;
*sum=0;
return 0;
}
if(tl>=l && tr<=r){
*gcd=t[v].gcd;
*ma=t[v].max;
*sum=t[v].sum;
return (*gcd)*((*sum)-(*ma));
}
tm=(tl+tr)/2;
query(2*v,tl,tm,l,r,&g1,&m1,&s1);
query(2*v+1,tm+1,tr,l,r,&g2,&m2,&s2);
*gcd=CC(g1,g2);
*ma=max(m1,m2);
*sum=s1+s2;
return (*gcd)*((*sum)-(*ma));
}
void getp(long long N,long long*prim)
{
long long i,j,index=2,flag;
if(N<=1){
prim[0]=0;
return;}
if(N==2){
prim[0]=2;
prim[1]=0;
return;}
prim[0]=2;
prim[1]=3;
for(i=5;i<=N;i=i+2)
{
for(j=1,flag=1;prim[j]<=sqrt(i);j++)
{
if(i%prim[j]==0){
flag=0;
break;}
}
if(flag==1)
{prim[index]=i;
index++;}
}
prim[index]=0;
return;
}
long long CC(long long n, long long d)
{
if(n==0)
return d;
if(d==0)
return n;
while( 1 )
{
n = n % d;
if( n == 0 )
return d;
d = d % n;
if( d == 0 )
return n;
}
}
int max(int x,int y){
return (x>y)?x:y;
}
int min(int x,int y){
return (x<y)?x:y;
}
int abss(int x){
return (x<0)?-x:x;
}
int search(tree_node *root,int data){
if(!root)
return INF;
if(root->data==data)
return root->real;
if(data<root->data)
return search(root->left,data);
return search(root->right,data);
}
void left_rotate(tree_node **root,tree_node *x){
tree_node *y;
y=x->right;
if(!y) return;
x->right=y->left;
if(y->left)
y->left->parent=x;
y->parent=x->parent;
if(x->parent==NULL) *root=y;
else
if(x==x->parent->left)
x->parent->left=y;
else
x->parent->right=y;
y->left=x;
x->parent=y;
return;
}
void right_rotate(tree_node **root,tree_node *y){
tree_node *x;
x=y->left;
if(!x) return;
y->left=x->right;
if(x->right)
x->right->parent=y;
x->parent=y->parent;
if(y->parent==NULL) *root=x;
else
if(y==y->parent->right)
y->parent->right=x;
else
y->parent->left=x;
x->right=y;
y->parent=x;
return;
}
void reconstruct(tree_node **root,tree_node *x){
tree_node *y,*z;
y=x->parent;
z=x->parent->parent;
x->colour=black;
z->colour=red;
x->parent=z->parent;
if(z->parent==NULL)
*root=x;
else if(z==z->parent->left)
z->parent->left=x;
else
z->parent->right=x;
if(z->left==y){
x->left=y;
x->right=z;
}
else{
x->left=z;
x->right=y;
}
y->parent=z->parent=x;
y->left=y->right=z->left=z->right=NULL;
return;
}
int normal_insert(tree_node **root,tree_node *x){
if(*root==NULL)
*root=x;
else if((*root)->data==x->data)
return 0;
else{
x->parent=*root;
if((*root)->data>x->data)
return normal_insert(&((*root)->left),x);
else
return normal_insert(&((*root)->right),x);
}
return 1;
}
void insert(tree_node **root,tree_node *x){
if(!normal_insert(root,x))
return;
tree_node *y;
x->colour=red;
while(x!=*root && x->parent->colour==red){
if(x->parent==x->parent->parent->left){
y=x->parent->parent->right;
if(!y)
if(x==x->parent->left){
x->parent->colour=black;
x->parent->parent->colour=red;
right_rotate(root,x->parent->parent);
}
else{
y=x->parent;
reconstruct(root,x);
x=y;
}
else if(y->colour==red){
x->parent->colour=black;
y->colour=black;
x->parent->parent->colour=red;
x=x->parent->parent;
}
else{
if(x==x->parent->right){
x=x->parent;
left_rotate(root,x);
}
x->parent->colour=black;
x->parent->parent->colour=red;
right_rotate(root,x->parent->parent);
}
}
else{
y=x->parent->parent->left;
if(!y)
if(x==x->parent->right){
x->parent->colour=black;
x->parent->parent->colour=red;
left_rotate(root,x->parent->parent);
}
else{
y=x->parent;
reconstruct(root,x);
x=y;
}
else if(y->colour==red){
x->parent->colour=black;
y->colour=black;
x->parent->parent->colour=red;
x=x->parent->parent;
}
else{
if(x==x->parent->left){
x=x->parent;
right_rotate(root,x);
}
x->parent->colour=black;
x->parent->parent->colour=red;
left_rotate(root,x->parent->parent);
}
}
}
(*root)->colour=black;
return;
}
void sort_a(int*a,int size,int*new_size){
if (size < 2){
(*new_size)=size;
return;
}
int m = (size+1)/2,i;
int *left,*right;
left=(int*)malloc(m*sizeof(int));
right=(int*)malloc((size-m)*sizeof(int));
for(i=0;i<m;i++)
left[i]=a[i];
for(i=0;i<size-m;i++)
right[i]=a[i+m];
int new_l_size=0,new_r_size=0;
sort_a(left,m,&new_l_size);
sort_a(right,size-m,&new_r_size);
merge(a,left,right,new_l_size,new_r_size,new_size);
free(left);
free(right);
return;
}
void merge(int*a,int*left,int*right,int left_size, int right_size,int*new_size){
int i = 0, j = 0,index=0;
while (i < left_size|| j < right_size) {
if (i == left_size) {
a[index++] = right[j];
j++;
} else if (j == right_size) {
a[index++] = left[i];
i++;
} else if (left[i] <= right[j]) {
a[index++] = left[i];
i++;
} else {
a[index++] = right[j];
j++;
}
if(index>1&&a[index-2]==a[index-1])
index--;
}
(*new_size)=index;
return;
}
void init( int n )
{
N = 1;
while( N < n ) N *= 2;
int i;
for( i = 1; i < N + n; i++ ) tree[i] = -1000000000000000000LL;
}
int range_sum( int i, int j )
{
int ansi;
long long ans = -1000000000000000000LL;
for( i += N, j += N; i <= j; i = ( i + 1 ) / 2, j = ( j - 1 ) / 2 )
{
if( i % 2 == 1 )
if(tree[i]>ans){
ans=tree[i];
ansi=treei[i];
}
if( j % 2 == 0 )
if(tree[j]>ans){
ans=tree[j];
ansi=treei[j];
}
}
return ansi;
}
void update( int i, long long val )
{
int j;
for( j = i + N; j; j /= 2 )
if(val>tree[j]){
tree[j]=val;
treei[j]=i;
}
}
In Python3 :
from math import gcd
def parseInput(f):
return [f(x) for x in input().split()]
n=int(input())
array=parseInput(int)
stack=[]
answer=float('-inf')
for number in array:
for i in range(len(stack)):
stack[i][0]=gcd(abs(stack[i][0]),abs(number))
stack[i][1]+=number
if number > stack[i][2]:
stack[i][1]-=number-stack[i][2]
stack[i][2]=number
stack.append([number,0,number])
newStack=[]
for i in range(len(stack)):
if newStack and newStack[-1][0] == stack[i][0]:
if newStack[-1][1] <= stack[i][1]:
if newStack[-1][1]+newStack[-1][2] > stack[i][1]+stack[i][2]:
newStack.append(stack[i])
continue
newStack[-1][1]=stack[i][1]
newStack[-1][2]=stack[i][2]
else:
newStack.append(stack[i])
stack = newStack[:]
answer=max(answer,max(abs(stack[i][0])*stack[i][1] for i in range(len(stack))))
print(answer)
View More Similar Problems
Mr. X and His Shots
A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M
View Solution →Jim and the Skyscrapers
Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space
View Solution →Palindromic Subsets
Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t
View Solution →Counting On a Tree
Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n
View Solution →Polynomial Division
Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie
View Solution →Costly Intervals
Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the
View Solution →