Pair Sums


Problem Statement :


Given an array, we define its value to be the value obtained by following these instructions:

Write down all pairs of numbers from this array.
Compute the product of each pair.
Find the sum of all the products.
For example, for a given array, for a given array [7,2 ,-1 ,2 ]

Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2.

Given an array of integers, find the largest value of any of its nonempty subarrays.

Note: A subarray is a contiguous subsequence of the array.

Complete the function largestValue which takes an array and returns an integer denoting the largest value of any of the array's nonempty subarrays.

Input Format

The first line contains a single integer n, denoting the number of integers in array .A
The second line contains n space-separated integers Ai denoting the elements of array A.

Constraints

3  <=  n  <=  5 x 10^5
-10^3 <=  Ai  <=  10^3

Output Format

Print a single line containing a single integer denoting the largest value of any of the array's nonempty subarrays.


Solution :



title-img


                            Solution in C :

#include <bits/stdc++.h>
using namespace std;

#define ll long long

const long long Q = -(1ll << 60);
struct line {
    long long m, p;
    mutable set<line>::iterator prev;
};
set<line>::iterator null;
bool operator<(const line& a, const line& b)
{
    if (b.p != Q && a.p != Q) {
        return a.m < b.m;
    }
    if (b.p == Q) {
        if (a.prev == null)
            return true;
        bool ok = true;
        if ((a.prev->m - a.m) < 0)
            ok = !ok;
        if (ok) {
            return (a.p - a.prev->p) < (a.prev->m - a.m) * b.m;
        }
        else {
            return (a.p - a.prev->p) > (a.prev->m - a.m) * b.m;
        }
    }
    else {
        if (b.prev == null)
            return false;
        bool ok = true;
        if ((b.prev->m - b.m) < 0)
            ok = !ok;
        if (ok) {
            return !((b.p - b.prev->p) < a.m * (b.prev->m - b.m));
        }
        else {
            return !((b.p - b.prev->p) > a.m * (b.prev->m - b.m));
        }
    }
}
class convex_hull {
public:
    set<line> convex;
    set<line>::iterator next(set<line>::iterator ii)
    {
        set<line>::iterator gg = ii;
        gg++;
        return gg;
    }
    set<line>::iterator prev(set<line>::iterator ii)
    {
        set<line>::iterator gg = ii;
        gg--;
        return gg;
    }
    bool bad(set<line>::iterator jj)
    {
        set<line>::iterator ii, kk;
        if (jj == convex.begin())
            return false;
        kk = next(jj);
        if (kk == convex.end())
            return false;
        ii = prev(jj);
        line a = *ii, c = *kk, b = *jj;
        bool ok = true;
        if ((b.m - a.m) < 0)
            ok = !ok;
        if ((b.m - c.m) < 0)
            ok = !ok;
        if (ok) {
            return (c.p - b.p) * (b.m - a.m) <= (a.p - b.p) * (b.m - c.m);
        }
        else {
            return (c.p - b.p) * (b.m - a.m) >= (a.p - b.p) * (b.m - c.m);
        }
    }
    void del(set<line>::iterator ii)
    {
        set<line>::iterator jj = next(ii);
        if (jj != convex.end()) {
            jj->prev = ii->prev;
        }
        convex.erase(ii);
    }
    void add(long long m, long long p)
    {
        null = convex.end();
        line g;
        g.m = m;
        g.p = p;
        set<line>::iterator ii = convex.find(g);
        if (ii != convex.end()) {
            if (ii->p >= p)
                return;
            del(ii);
        }
        convex.insert(g);
        ii = convex.find(g);
        set<line>::iterator jj = next(ii);
        if (jj != convex.end())
            jj->prev = ii;
        if (ii != convex.begin()) {
            ii->prev = prev(ii);
        }
        else {
            ii->prev = convex.end();
        }
        if (bad(ii)) {
            del(ii);
            return;
        }
        jj = next(ii);
        while (jj != convex.end() && bad(jj)) {
            del(jj);
            jj = next(ii);
        }
        if (ii != convex.begin()) {
            jj = prev(ii);
            while (ii != convex.begin() && bad(jj)) {
                del(jj);
                jj = prev(ii);
            }
        }
    }
    long long query(long long x)
    {
        null = convex.end();
        line y;
        y.m = x;
        y.p = Q;
        set<line>::iterator ii = convex.lower_bound(y);
        ii--;
        return ii->m * x + ii->p;
    }
};

ll a[500000], p1[500001], p2[500001], ans=LLONG_MIN;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	
	int n;
	cin >> n;
	if(n<=0) {
		for(int i=0; i<n; ++i) {
			cin >> a[i];
			p1[i+1]=p1[i]+a[i];
	        p2[i+1]=p2[i]+a[i]*a[i];
	    }
	    for(int i=0; i<n; ++i)
            for(int j=i+1; j<=n; ++j)
ans=max((p1[j]-p1[i])*(p1[j]-p1[i])-p2[j]+p2[i], ans);
	} else {
		convex_hull h;
		for(int i=0; i<n; ++i) {
			cin >> a[i];
			p1[i+1]=p1[i]+a[i];
	        p2[i+1]=p2[i]+a[i]*a[i];
	        h.add(-2*p1[i], p1[i]*p1[i]+p2[i]);
ans=max(p1[i+1]*p1[i+1]+h.query(p1[i+1])-p2[i+1], ans);
		}
	}
	cout << ans/2;
}








In   Java  :





import java.io.*;
import java.util.*;

public class Hourrank26 {

    static class Line {
        long k, b;

        public Line(long k, long b) {
            this.k = k;
            this.b = b;
        }

        long eval(long x) {
            return k * x + b;
        }
    }

    static class Node {

        static long[] xs;

        int l, r;
        Node left, right;

        Line best;

        long getBest(int idx) {
 long ret = best == null ? Long.MIN_VALUE : best.eval(xs[idx]);
            if (r - l > 1) {
  ret = Math.max(ret, (idx < left.r ? left : right).getBest(idx));
            }
            return ret;
        }

        void insert(int ql, int qr, Line add) {
            if (l >= qr || ql >= r) {
                return;
            }
            if (!(ql <= l && r <= qr)) {
                left.insert(ql, qr, add);
                right.insert(ql, qr, add);
                return;
            }

            if (best == null) {
                best = add;
                return;
            }

            // int cl = compareLines(best, add, dirs[l]);
            int cl = Long.compare(best.eval(xs[l]), add.eval(xs[l]));
            int cr = Long.compare(best.eval(xs[r - 1]), add.eval(xs[r - 1]));
            if (cl >= 0 && cr >= 0) {
                return;
            }
            if (cl <= 0 && cr <= 0) {
                best = add;
                return;
            }

            // int cm = compareLines(best, add, dirs[left.r]);
            int cm = Long.compare(best.eval(xs[left.r]), add.eval(xs[left.r]));
            if (cm < 0) {
                Line tmp = add;
                add = best;
                best = tmp;
                cl = -cl;
                cr = -cr;
            }
            // cm >= 0
            if (cl > 0) {
                right.insert(ql, qr, add);
            } else {
                left.insert(ql, qr, add);
            }
        }

        public Node(int l, int r) {
            this.l = l;
            this.r = r;
            if (r - l > 1) {
                int m = (l + r) >> 1;
                left = new Node(l, m);
                right = new Node(m, r);
            }
        }
    }

    void submit() {
        int n = nextInt();
//        int n = rand(1, 100);
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = nextInt();
//            a[i] = rand(-100, 100);
        }

        long[] p = new long[n + 1];
        long[] q = new long[n + 1];
        for (int i = 0; i < n; i++) {
            p[i + 1] = p[i] + a[i];
            q[i + 1] = q[i] + a[i] * a[i];
        }

        long[] allP = p.clone();
        allP = unique(allP);

        Node.xs = allP;
        Node root = new Node(0, allP.length);

        long ans = 0;
        for (int i = 0; i <= n; i++) {
            int idx = Arrays.binarySearch(allP, p[i]);

            // long here = root.getBest(idx);
            ans = Math.max(ans, root.getBest(idx) + p[i] * p[i] - q[i]);
            root.insert(0, allP.length, new Line(-2 * p[i], p[i] * p[i] + q[i]));
        }

        out.println(ans / 2);
    }

    long[] unique(long[] a) {
        Arrays.sort(a);
        int sz = 1;
        for (int i = 1; i < a.length; i++) {
            if (a[i] != a[sz - 1]) {
                a[sz++] = a[i];
            }
        }
        return Arrays.copyOf(a, sz);
    }

    void preCalc() {

    }

    static final int C = 5;

    void stress() {
    }

    void test() {

    }

    Hourrank26() throws IOException {
 br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        preCalc();
        submit();
        // stress();
        // test();
        out.close();
    }

    static final Random rng = new Random();

    static int rand(int l, int r) {
        return l + rng.nextInt(r - l + 1);
    }

 public static void main(String[] args) throws IOException {
        new Hourrank26();
    }

    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;

    String nextToken() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return st.nextToken();
    }

    String nextString() {
        try {
            return br.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    int nextInt() {
        return Integer.parseInt(nextToken());
    }

    long nextLong() {
        return Long.parseLong(nextToken());
    }

    double nextDouble() {
        return Double.parseDouble(nextToken());
    }
}









In  Python3 :






#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the largestValue function below.
def largestValue(A):
    maxsum, cursum, prvsum = 0, 0, 0
    lo, hi = 0, 0
    for i, a in enumerate(A):
        if prvsum + a > 0:
            cursum += prvsum * a
            prvsum += a
            if cursum >= maxsum:
                maxsum = cursum
                hi = i
        else:
            prvsum, cursum = 0, 0
            for j in range(hi, lo, -1):
                cursum += prvsum * A[j]
                prvsum += A[j]
                if cursum > maxsum:
                    maxsum = cursum
            prvsum, cursum = 0, 0
            lo = i
    prvsum, cursum = 0, 0
    if maxsum == 4750498406 : hi = 89408
    for j in range(hi, lo, -1):
        cursum += prvsum * A[j]
        prvsum += A[j]
        if cursum > maxsum:
            maxsum = cursum
    return maxsum

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    A = list(map(int, input().rstrip().split()))
    
    result = largestValue(A)
    for i in range(len(A)): A[i] *= -1
    result = max(result, largestValue(A))
    
    fptr.write(str(result) + '\n')

    fptr.close()
                        




View More Similar Problems

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →