Open In App

K-th Largest Sum Contiguous Subarray

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers that has both negative and positive numbers.

Examples: 

Input: a[] = {20, -5, -1}, K = 3
Output: 14
Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) 
so the 3rd largest sum is 14.

Input: a[] = {10, -10, 20, -40}, k = 6
Output: -10
Explanation: The 6th largest sum among
sum of all contiguous subarrays is -10.

Brute force Approach: Store all the contiguous sums in another array and sort it and print the Kth largest. But in the case of the number of elements being large, the array in which we store the contiguous sums will run out of memory as the number of contiguous subarrays will be large (quadratic order)

C++
// C++ program to find the K-th largest sum
// of subarray
#include <bits/stdc++.h>
using namespace std;

// Function to calculate Kth largest element
// in contiguous subarray sum
int kthLargestSum(int arr[], int N, int K)
{
    vector<int> result;

    // Generate all subarrays
    for (int i = 0; i < N; i++) {
        int sum = 0;
        for (int j = i; j < N; j++) {
            sum += arr[j];
            result.push_back(sum);
        }
    }

    // Sort in decreasing order
    sort(result.begin(), result.end(), greater<int>());

    // return the Kth largest sum
    return result[K - 1];
}

// Driver's code
int main()
{
    int a[] = { 20, -5, -1 };
    int N = sizeof(a) / sizeof(a[0]);
    int K = 3;

    // Function call
    cout << kthLargestSum(a, N, K);
    return 0;
}

// This code is contributed by hkdass001
Java
// Java program to find the K-th largest sum
// of subarray

import java.util.*;

public class GFG {

    // Function to calculate Kth largest element
    // in contiguous subarray sum
    static int kthLargestSum(int arr[], int N, int K)
    {
        ArrayList<Integer> result = new ArrayList<>();

        // Generate all subarrays
        for (int i = 0; i < N; i++) {
            int sum = 0;
            for (int j = i; j < N; j++) {
                sum += arr[j];
                result.add(sum);
            }
        }

        // Sort in decreasing order
        Collections.sort(result,
                         Collections.reverseOrder());

        // return the Kth largest sum
        return result.get(K - 1);
    }

    // Driver's code
    public static void main(String[] args)
    {
        int a[] = { 20, -5, -1 };
        int N = a.length;
        int K = 3;

        // Function call
        System.out.println(kthLargestSum(a, N, K));
    }
}

// This code is contributed by Karandeep1234
Python
# Python program to find the K-th largest sum of subarray
# Function to calculate Kth largest element
# in contiguous subarray sum

def kthLargestSum(arr, N, K):
  result = []
  #  Generate all subarrays
  for i in range(N):
      sum = 0
      for j in range(i, N):
          sum += arr[j]
          result.append(sum)

  # Sort in decreasing order
  result.sort(reverse=True)

  # return the Kth largest sum
  return result[K - 1]

# Driver's code
a = [ 20, -5, -1]
N = len(a)
K = 3

# Function call
print(kthLargestSum(a, N, K))

# This code is contributed by hardikkushwaha.
C#
// C# program to find the K-th largest sum
// of subarray

using System;
using System.Collections.Generic;

public class GFG {

    // Function to calculate Kth largest element
    // in contiguous subarray sum
    static int kthLargestSum(int[] arr, int N, int K)
    {
        List<int> result = new List<int>();

        // Generate all subarrays
        for (int i = 0; i < N; i++) {
            int sum = 0;
            for (int j = i; j < N; j++) {
                sum += arr[j];
                result.Add(sum);
            }
        }

        // Sort in decreasing order
        result.Sort();
        result.Reverse();

        // return the Kth largest sum
        return result[K - 1];
    }

    // Driver's code
    public static void Main(string[] args)
    {
        int[] a = { 20, -5, -1 };
        int N = a.Length;
        int K = 3;

        // Function call
        Console.WriteLine(kthLargestSum(a, N, K));
    }
}
// This code is contributed by Karandeep1234
Javascript
// Javascript program to find the K-th largest sum
// of subarray

// Function to calculate Kth largest element
// in contiguous subarray sum
function kthLargestSum(arr, N, K)
{
    let result=[];

    // Generate all subarrays
    for (let i = 0; i < N; i++) {
        let sum = 0;
        for (let j = i; j < N; j++) {
            sum += arr[j];
            result.push(sum);
        }
    }

    // Sort in decreasing order
    result.sort();
    result.reverse();

    // return the Kth largest sum
    return result[K - 1];
}

// Driver's code
    let a = [20, -5, -1 ];
    let N = a.length;
    let K = 3;

    // Function call
    document.write(kthLargestSum(a, N, K));
  

Output
14

Time Complexity: O(n2*log(n2))
Auxiliary Space: O(n)

Kth largest sum contiguous subarray using Min-Heap:

The key idea is to store the pre-sum of the array in a sum[] array. One can find the sum of contiguous subarray from index i to j as sum[j] – sum[i-1]. Now generate all possible contiguous subarray sums and push them into the Min-Heap only if the size of Min-Heap is less than K or the current sum is greater than the root of the Min-Heap. In the end, the root of the Min-Heap is the required answer

Follow the given steps to solve the problem using the above approach:

  • Create a prefix sum array of the input array
  • Create a Min-Heap that stores the subarray sum
  • Iterate over the given array using the variable i such that 1 <= i <= N, here i denotes the starting point of the subarray
    • Create a nested loop inside this loop using a variable j such that i <= j <= N, here j denotes the ending point of the subarray
      • Calculate the sum of the current subarray represented by i and j, using the prefix sum array
      • If the size of the Min-Heap is less than K, then push this sum into the heap
      • Otherwise, if the current sum is greater than the root of the Min-Heap, then pop out the root and push the current sum into the Min-Heap
  • Now the root of the Min-Heap denotes the Kth largest sum, Return it

Below is the implementation of the above approach:

C++
// C++ program to find the K-th largest sum
// of subarray
#include <bits/stdc++.h>
using namespace std;

// Function to calculate Kth largest element
// in contiguous subarray sum
int kthLargestSum(int arr[], int N, int K)
{
    // array to store prefix sums
    int sum[N + 1];
    sum[0] = 0;
    sum[1] = arr[0];
    for (int i = 2; i <= N; i++)
        sum[i] = sum[i - 1] + arr[i - 1];

    // priority_queue of min heap
    priority_queue<int, vector<int>, greater<int> > Q;

    // loop to calculate the contiguous subarray
    // sum position-wise
    for (int i = 1; i <= N; i++) {

        // loop to traverse all positions that
        // form contiguous subarray
        for (int j = i; j <= N; j++) {
            // calculates the contiguous subarray
            // sum from j to i index
            int x = sum[j] - sum[i - 1];

            // if queue has less than k elements,
            // then simply push it
            if (Q.size() < K)
                Q.push(x);

            else {
                // it the min heap has equal to
                // k elements then just check
                // if the largest kth element is
                // smaller than x then insert
                // else its of no use
                if (Q.top() < x) {
                    Q.pop();
                    Q.push(x);
                }
            }
        }
    }

    // the top element will be then kth
    // largest element
    return Q.top();
}

// Driver's code
int main()
{
    int a[] = { 10, -10, 20, -40 };
    int N = sizeof(a) / sizeof(a[0]);
    int K = 6;

    // Function call
    cout << kthLargestSum(a, N, K);
    return 0;
}
Java
// Java program to find the K-th
// largest sum of subarray
import java.util.*;

class KthLargestSumSubArray {
  
    // function to calculate Kth largest
    // element in contiguous subarray sum
    static int kthLargestSum(int arr[], int N, int K)
    {
        // array to store prefix sums
        int sum[] = new int[N + 1];
        sum[0] = 0;
        sum[1] = arr[0];
        for (int i = 2; i <= N; i++)
            sum[i] = sum[i - 1] + arr[i - 1];

        // priority_queue of min heap
        PriorityQueue<Integer> Q
            = new PriorityQueue<Integer>();

        // loop to calculate the contiguous subarray
        // sum position-wise
        for (int i = 1; i <= N; i++) {

            // loop to traverse all positions that
            // form contiguous subarray
            for (int j = i; j <= N; j++) {
                // calculates the contiguous subarray
                // sum from j to i index
                int x = sum[j] - sum[i - 1];

                // if queue has less than k elements,
                // then simply push it
                if (Q.size() < K)
                    Q.add(x);

                else {
                    // it the min heap has equal to
                    // k elements then just check
                    // if the largest kth element is
                    // smaller than x then insert
                    // else its of no use
                    if (Q.peek() < x) {
                        Q.poll();
                        Q.add(x);
                    }
                }
            }
        }

        // the top element will be then kth
        // largest element
        return Q.poll();
    }

    // Driver's Code
    public static void main(String[] args)
    {
        int a[] = new int[] { 10, -10, 20, -40 };
        int N = a.length;
        int K = 6;

        // Function call
        System.out.println(kthLargestSum(a, N, K));
    }
}

/* This code is contributed by Danish Kaleem */
Python
# Python program to find the K-th largest sum
# of subarray
import heapq

# function to calculate Kth largest element
# in contiguous subarray sum


def kthLargestSum(arr, N, K):

    # array to store prefix sums
    sum = []
    sum.append(0)
    sum.append(arr[0])
    for i in range(2, N + 1):
        sum.append(sum[i - 1] + arr[i - 1])

    # priority_queue of min heap
    Q = []
    heapq.heapify(Q)

    # loop to calculate the contiguous subarray
    # sum position-wise
    for i in range(1, N + 1):

        # loop to traverse all positions that
        # form contiguous subarray
        for j in range(i, N + 1):
            x = sum[j] - sum[i - 1]

            # if queue has less than k elements,
            # then simply push it
            if len(Q) < K:
                heapq.heappush(Q, x)
            else:
                # it the min heap has equal to
                # k elements then just check
                # if the largest kth element is
                # smaller than x then insert
                # else its of no use
                if Q[0] < x:
                    heapq.heappop(Q)
                    heapq.heappush(Q, x)

    # the top element will be then kth
    # largest element
    return Q[0]


# Driver's code
if __name__ == "__main__":
    a = [10, -10, 20, -40]
    N = len(a)
    K = 6

    # Function call
    print(kthLargestSum(a, N, K))


# This code is contributed by Kumar Suman
C#
// C# program to find the K-th
// largest sum of subarray

using System;
using System.Collections.Generic;
public class KthLargestSumSubArray {

    // function to calculate Kth largest
    // element in contiguous subarray sum
    static int kthLargestSum(int[] arr, int N, int K)
    {

        // array to store prefix sums
        int[] sum = new int[N + 1];
        sum[0] = 0;
        sum[1] = arr[0];
        for (int i = 2; i <= N; i++)
            sum[i] = sum[i - 1] + arr[i - 1];

        // priority_queue of min heap
        List<int> Q = new List<int>();

        // loop to calculate the contiguous subarray
        // sum position-wise
        for (int i = 1; i <= N; i++) {

            // loop to traverse all positions that
            // form contiguous subarray
            for (int j = i; j <= N; j++) {
                // calculates the contiguous subarray
                // sum from j to i index
                int x = sum[j] - sum[i - 1];

                // if queue has less than k elements,
                // then simply push it
                if (Q.Count < K)
                    Q.Add(x);

                else {
                    // it the min heap has equal to
                    // k elements then just check
                    // if the largest kth element is
                    // smaller than x then insert
                    // else its of no use
                    Q.Sort();
                    if (Q[0] < x) {
                        Q.RemoveAt(0);
                        Q.Add(x);
                    }
                }
                Q.Sort();
            }
        }

        // the top element will be then Kth
        // largest element
        return Q[0];
    }

    // Driver's Code
    public static void Main(String[] args)
    {
        int[] a = new int[] { 10, -10, 20, -40 };
        int N = a.Length;
        int K = 6;

        // Function call
        Console.WriteLine(kthLargestSum(a, N, K));
    }
}

// This code contributed by Rajput-Ji
JavaScript
// Javascript program to find the k-th largest sum
// of subarray

// function to calculate kth largest element
// in contiguous subarray sum
function kthLargestSum(arr, n, k)
{
    // array to store prefix sums
    var sum = new Array(n + 1);
    sum[0] = 0;
    sum[1] = arr[0];
    for (var i = 2; i <= n; i++)
        sum[i] = sum[i - 1] + arr[i - 1];

    // priority_queue of min heap
    var Q = [];

    // loop to calculate the contiguous subarray
    // sum position-wise
    for (var i = 1; i <= n; i++)
    {

        // loop to traverse all positions that
        // form contiguous subarray
        for (var j = i; j <= n; j++)
        {
            // calculates the contiguous subarray
            // sum from j to i index
            var x = sum[j] - sum[i - 1];

            // if queue has less than k elements,
            // then simply push it
            if (Q.length < k)
                Q.push(x);

            else
            {
                // it the min heap has equal to
                // k elements then just check
                // if the largest kth element is
                // smaller than x then insert
                // else its of no use
                Q.sort();
                if (Q[0] < x)
                {
                    Q.pop();
                    Q.push(x);
                }
            }
            
            Q.sort();
        }
    }

    // the top element will be then kth
    // largest element
    return Q[0];
}

// Driver program to test above function
var a = [ 10, -10, 20, -40 ];
var n = a.length;
var k = 6;

// calls the function to find out the
// k-th largest sum
document.write(kthLargestSum(a, n, k));

Output
-10

Time Complexity: O(N2 log K) 
Auxiliary Space: O(N), but this can be reduced to O(K) for min-heap and we can store the prefix sum array in the input array itself as it is of no use.

Kth largest sum contiguous subarray using  Prefix Sum and Sorting approach:

The basic idea behind the Prefix Sum and Sorting approach is to create a prefix sum array and use it to calculate all possible subarray sums. The subarray sums are then sorted in decreasing order using the sort() function. Finally, the K-th largest sum of contiguous subarray is returned from the sorted vector of subarray sums.

Follow the Steps to implement the approach:

  1. Create a prefix sum array of the given array.
  2. Create a vector to store all possible subarray sums by subtracting prefix sums.
  3. Sort the vector of subarray sums in decreasing order using the sort() function.
  4. Return the K-th largest sum of contiguous subarray from the sorted vector of subarray sums.

Below is the implementation of the above approach:

C++
// C++ code to implement Prefix sum approach
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// The main function to find the K-th largest sum of
// contiguous subarray using Prefix Sum and Sorting
// approach.
int kthLargestSum(vector<int>& arr, int k)
{
    int n = arr.size();

    // Create a prefix sum array.
    vector<int> prefixSum(n + 1);
    prefixSum[0] = 0;
    for (int i = 1; i <= n; i++) {
        prefixSum[i] = prefixSum[i - 1] + arr[i - 1];
    }

    // Create a vector to store all possible subarray sums.
    vector<int> subarraySums;
    for (int i = 0; i <= n; i++) {
        for (int j = i + 1; j <= n; j++) {
            subarraySums.push_back(prefixSum[j]
                                   - prefixSum[i]);
        }
    }

    // Sort the subarray sums in decreasing order.
    sort(subarraySums.begin(), subarraySums.end(),
         greater<int>());

    // Return the K-th largest sum of contiguous subarray.
    return subarraySums[k - 1];
}
// Driver Code
int main()
{
    vector<int> arr = { 10, -10, 20, -40 };
    int k = 6;
    cout << kthLargestSum(arr, k)
         << endl; // expected output is -10

    return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GFG {
    // The main function to find the K-th largest sum of
    // contiguous subarray using Prefix Sum and Sorting
    // approach.
    public static int kthLargestSum(List<Integer> arr, int k) {
        int n = arr.size();

        // Create a prefix sum array.
        List<Integer> prefixSum = new ArrayList<>(n + 1);
        prefixSum.add(0);
        for (int i = 1; i <= n; i++) {
            prefixSum.add(prefixSum.get(i - 1) + arr.get(i - 1));
        }

        // Create a list to store all possible subarray sums.
        List<Integer> subarraySums = new ArrayList<>();
        for (int i = 0; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                subarraySums.add(prefixSum.get(j) - prefixSum.get(i));
            }
        }

        // Sort the subarray sums in decreasing order.
        Collections.sort(subarraySums, Collections.reverseOrder());

        // Return the K-th largest sum of contiguous subarray.
        return subarraySums.get(k - 1);
    }

    // Driver Code
    public static void main(String[] args) {
        List<Integer> arr = List.of(10, -10, 20, -40);
        int k = 6;
        System.out.println(kthLargestSum(arr, k)); // expected output is -10
    }
}
Python
# Python code to implement Prefix sum approach
import heapq

# The main function to find the K-th largest sum of
# contiguous subarray using Prefix Sum and Sorting
# approach.
def kthLargestSum(arr, k):
    n = len(arr)

    # Create a prefix sum array.
    prefixSum = [0] * (n + 1)
    for i in range(1, n+1):
        prefixSum[i] = prefixSum[i - 1] + arr[i - 1]

    # Create a heap to store K largest subarray sums.
    subarraySums = []
    heapq.heapify(subarraySums)
    for i in range(n + 1):
        for j in range(i + 1, n + 1):
            subarraySum = prefixSum[j] - prefixSum[i]
            if len(subarraySums) < k:
                heapq.heappush(subarraySums, subarraySum)
            else:
                if subarraySum > subarraySums[0]:
                    heapq.heapreplace(subarraySums, subarraySum)

    # Return the K-th largest sum of contiguous subarray.
    return subarraySums[0]

# Driver Code
if __name__ == '__main__':
    arr = [10, -10, 20, -40]
    k = 6
    print(kthLargestSum(arr, k)) # expected output is -10
# This code is contributed by Abhay_Mishra
C#
// C# code to implement Prefix sum approach

using System;
using System.Collections.Generic;
using System.Linq;

public class GFG{
    // The main function to find the K-th largest sum of
    // contiguous subarray using Prefix Sum and Sorting
    // approach.
    public static int kthLargestSum(List<int> arr, int k){
        int n = arr.Count;

        // Create a prefix sum array.
        List<int> prefixSum = new List<int>(n + 1);
        prefixSum.Add(0);
        for (int i = 1; i <= n; i++){
            prefixSum.Add(prefixSum[i - 1] + arr[i - 1]);
        }

        // Create a list to store all possible subarray sums.
        List<int> subarraySums = new List<int>();
        for (int i = 0; i <= n; i++){
            for (int j = i + 1; j <= n; j++){
                subarraySums.Add(prefixSum[j] - prefixSum[i]);
            }
        }

        // Sort the subarray sums in decreasing order.
        subarraySums.Sort();
        subarraySums.Reverse();

        // Return the K-th largest sum of contiguous subarray.
        return subarraySums[k - 1];
    }

    // Driver Code to test above function
    public static void Main(string[] args){
        List<int> arr = new List<int> { 10, -10, 20, -40 };
        int k = 6;
        Console.WriteLine(kthLargestSum(arr, k)); // expected output is -10
    }
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
Javascript
// JavaScript code to implement Prefix sum approach

// The main function to find the K-th largest sum of
// contiguous subarray using Prefix Sum and Sorting
// approach.
function kthLargestSum(arr, k) {
    let n = arr.length;

    // Create a prefix sum array.
    let prefixSum = new Array(n + 1).fill(0);
    prefixSum[0] = 0;
    for (let i = 1; i <= n; i++) {
        prefixSum[i] = prefixSum[i - 1] + arr[i - 1];
    }

    // Create an array to store all possible subarray sums.
    let subarraySums = [];
    for (let i = 0; i <= n; i++) {
        for (let j = i + 1; j <= n; j++) {
            subarraySums.push(prefixSum[j] - prefixSum[i]);
        }
    }

    // Sort the subarray sums in decreasing order.
    subarraySums.sort((a, b) => b - a);

    // Return the K-th largest sum of contiguous subarray.
    return subarraySums[k - 1];
}

// Driver Code
let arr = [10, -10, 20, -40];
let k = 6;
console.log(kthLargestSum(arr, k)); // expected output is -10

Output
-10

Time Complexity: O(n^2 log n) ,The time complexity of the above code for the Prefix Sum and Sorting approach is O(n^2logn), where n is the size of the input array. This is due to the nested loop used to calculate all possible subarray sums and the sort() function used to sort the vector of subarray sums.

Auxiliary Space: O(n^2), The auxiliary space complexity of the above code is O(n). This is due to the creation of the prefix sum array(O(n)) and the vector to store all possible subarray sums(O(n^2))

 



Previous Article
Next Article

Similar Reads

Largest Sum Contiguous Subarray having unique elements
Given an array arr[] of N positive integers, the task is to find the subarray having maximum sum among all subarrays having unique elements and print its sum. Input arr[] = {1, 2, 3, 3, 4, 5, 2, 1}Output: 15Explanation:The subarray having maximum sum with distinct element is {3, 4, 5, 2, 1}.Therefore, sum is = 3 + 4 + 5 + 2 + 1 = 15 Input: arr[] =
15+ min read
C++ Program to Find the K-th Largest Sum Contiguous Subarray
Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers. Examples:  Input: a[] = {20, -5, -1} k = 3 Output: 14 Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the 3rd largest sum is 14. Input: a[] = {10, -10, 20,
3 min read
Java Program to Find the K-th Largest Sum Contiguous Subarray
Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers. Examples: Input: a[] = {20, -5, -1} k = 3 Output: 14 Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the 3rd largest sum is 14. Input: a[] = {10, -10, 20, -
3 min read
Python3 Program to Find the K-th Largest Sum Contiguous Subarray
Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers. Examples:  Input: a[] = {20, -5, -1} k = 3 Output: 14 Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the 3rd largest sum is 14. Input: a[] = {10, -10, 20,
3 min read
Largest sum contiguous subarray by adding S exactly at K different positions
Given an array arr[] of length N, the task is to find the largest sum contiguous subarray by adding an integer S exactly at K different positions in the array for every K from [0, N]. Examples: Input: arr[] = {4, 1, 3, 2}, S = 2Output: 10 12 14 16 18Explanation:For k = 0, the sum of the array it self is the maximum subarray sum since no negative el
10 min read
Range query for Largest Sum Contiguous Subarray
Given an array a[] of size N, and Q queries of two types 1 and 2. For the given query of: Type 1: given l and r (they are positions), and task is to print the Largest sum Contiguous Subarray Type 2: given type, index, and value, update aindex = value. Examples: Input: a[] = {-2, -3, 4, -1, -2, 1, 5, -3} 1st query : 1 5 8 2nd query : 2 1 10 3rd quer
15+ min read
Largest sum contiguous subarray having only non-negative elements
Given an integer array arr[], the task is to find the largest sum contiguous subarray of non-negative elements and return its sum. Examples: Input: arr[] = {1, 4, -3, 9, 5, -6} Output: 14 Explanation: Subarray [9, 5] is the subarray having maximum sum with all non-negative elements. Input: arr[] = {12, 0, 10, 3, 11} Output: 36 Recommended PracticeM
8 min read
Javascript Program for Largest Sum Contiguous Subarray
Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum. Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Kadane's Algorithm: Initialize: max_so_far = INT_MIN max_ending_here = 0 Loop for each element of the array (a) max_ending_here = m
5 min read
Largest sum contiguous increasing subarray
Given an array of n positive distinct integers. The problem is to find the largest sum of contiguous increasing subarray in O(n) time complexity. Examples : Input : arr[] = {2, 1, 4, 7, 3, 6}Output : 12Contiguous Increasing subarray {1, 4, 7} = 12Input : arr[] = {38, 7, 8, 10, 12}Output : 38Recommended PracticeGreedy FoxTry It!A simple solution is
15 min read
Largest Sum Contiguous Subarray (Kadane's Algorithm)
Given an array arr[] of size N. The task is to find the sum of the contiguous subarray within a arr[] with the largest sum.  Example: Input: arr = {-2,-3,4,-1,-2,1,5,-3}Output: 7Explanation: The subarray {4,-1, -2, 1, 5} has the largest sum 7. Input: arr = {2}Output: 2Explanation: The subarray {2} has the largest sum 1. Input: arr = {5,4,1,7,8}Outp
15 min read
Practice Tags :