Maximum Circular Sum [codingblocks]

You are given a one dimensional array that may contain both positive and negative integers, find the sum of contiguous subarray of numbers which has the largest sum. For example, if the given array is {-2, -5, 6, -2, -3, 1, 5, -6}, then the maximum subarray sum is 7.


Input Format
The first line consists of number of test cases T. Each test case consists of two lines.
The first line of each testcase contains a single integer N denoting the number of elements for the array A.
The second line of each testcase contains N space separated integers denoting the elements of the array.

Constraints
1 <= N <= 100000
1 <= t <= 20
-100000000 <= A[i] <= 100000000

Output Format
Output a single integer denoting the maximum subarray sum for each testcase in a new line.

Sample Input
2
4
1 2 3 4
3
-10 5 10

Sample Output
10
15

Explanation
For the first testcase, maximum subarray sum is generated by the entire array - 1+2+3+4 = 10
For the second testcase , maximum subarray sum is generated by the subarray {5,10} - 5+10 = 15


Java Code:


/*
Amit Kumar
12-12-2020
Logic picked from here: https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/178422/One-Pass
IDE Code: https://ide.geeksforgeeks.org/3BYVQZDwAH
*/


package array;
import java.util.Scanner;

public class Array_MaximumCircularSum {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        int testCase = scanner.nextInt();
        while (testCase-- >0) {
            int size = scanner.nextInt();
            int[] array = new int[size];
            for (int i=0; i<size; i++) {
                array[i] = scanner.nextInt();
            }
            System.out.println(maximumCircularSumHelper(array));
        }
    }

    private static int maximumCircularSumHelper(int[] array) {
        int max = array[0];
        int currMaxSum = array[0];

        int min = array[0];
        int currMinSum = array[0];

        int totalSum = array[0];

        for (int i=1; i<array.length; i++) {
            currMaxSum = Math.max(currMaxSum + array[i], array[i]);
            max = Math.max(currMaxSum, max);

            currMinSum = Math.min(currMinSum + array[i], array[i]);
            min = Math.min(currMinSum, min);

            totalSum = totalSum + array[i];
        }

        return max > 0 ? Math.max(max, totalSum - min): max;
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )