The Wayback Machine - https://web.archive.org/web/20240828040544/https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
Open In App

Maximum Subarray Sum – Kadane’s Algorithm

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 7
Explanation:

kadane-algorithm

Input: arr = {2}
Output: 2
Explanation: The subarray {2} has the largest sum 2.

Input: arr = {5,4,1,7,8}
Output: 25
Explanation: The subarray {5,4,1,7,8} has the largest sum 25.

Kadane’s Algorithm (O(n) time and O(1) Space):

The idea of Kadane’s algorithm is to maintain a variable max_ending_here that stores the maximum sum contiguous subarray ending at current index and a variable max_so_far stores the maximum sum of contiguous subarray found so far, Everytime there is a positive-sum value in max_ending_here compare it with max_so_far and update max_so_far if it is greater than max_so_far.

So the main Intuition behind Kadane’s Algorithm is, 

  • The subarray with negative sum is discarded (by assigning max_ending_here = 0 in code).
  • We carry subarray till it gives positive sum.

Pseudocode::

Initialize:
    max_so_far = INT_MIN
    max_ending_here = 0

Loop for each element of the array

  (a) max_ending_here = max_ending_here + a[i]
  (b) if(max_so_far < max_ending_here)
            max_so_far = max_ending_here
  (c) if(max_ending_here < 0)
            max_ending_here = 0
return max_so_far

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

int maxSubArraySum(vector<int>& a) {
    int max_so_far = INT_MIN, max_ending_here = 0;

    for (int i = 0; i < a.size(); i++) {      
        max_ending_here = max_ending_here + a[i];
      
        // If max_ending_here becomes more than 
        // the current result
        max_so_far = max(max_so_far, max_ending_here);
       
        // If max_ending_here becomes negative
        max_ending_here = max(max_ending_here, 0);
    }
    return max_so_far;
}

// Driver Code
int main() {
    vector<int> a = { -2, -3, 4, -1, -2, 1, 5, -3 };
    cout << "Maximum contiguous sum is " 
         <<  maxSubArraySum(a);
    return 0;
}
C
#include <stdio.h>
#include <limits.h>

int maxSubArraySum(int* a, int n) {
    int max_so_far = INT_MIN, max_ending_here = 0;

    for (int i = 0; i < n; i++) {      
        max_ending_here = max_ending_here + a[i];
      
        // If max_ending_here becomes more 
        // than the current result
        if (max_so_far < max_ending_here) {
            max_so_far = max_ending_here;
        }
       
        // If max_ending_here becomes negative
        if (max_ending_here < 0) {
            max_ending_here = 0;
        }
    }
    return max_so_far;
}

// Driver Code
int main() {
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    int n = sizeof(a) / sizeof(a[0]);

    printf("Maximum contiguous sum is %d", 
            maxSubArraySum(a, n));
    return 0;
}
Java
import java.util.Arrays;

public class GfG {

    static int maxSubArraySum(int[] a) {
        int maxSoFar = Integer.MIN_VALUE, maxEndingHere = 0;

        for (int i = 0; i < a.length; i++) {
            maxEndingHere += a[i];

            // Use Math.max to find the maximum 
            // of maxSoFar and maxEndingHere
            maxSoFar = Math.max(maxSoFar, maxEndingHere);

            // Use Math.max to reset maxEndingHere 
            // to 0 if it becomes negative
            maxEndingHere = Math.max(maxEndingHere, 0);
        }
        return maxSoFar;
    }

    public static void main(String[] args) {
        int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 };
        System.out.println("Maximum contiguous sum is " + maxSubArraySum(a));
    }
}
Python
def GFG(a, size):
    max_so_far = float('-inf')  
    # Use float('-inf') instead of maxint
    max_ending_here = 0
    for i in range(0, size):
        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
# Driver function to check the above function
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print("Maximum contiguous sum is", GFG(a, len(a)))
C#
// C# program to print largest
// contiguous array sum
using System;

class GFG {
    static int maxSubArraySum(int[] a)
    {
        int size = a.Length;
        int max_so_far = int.MinValue, 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;
    }

    // Driver code
    public static void Main()
    {
        int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 };
        Console.Write("Maximum contiguous sum is "
                      + maxSubArraySum(a));
    }
}

// This code is contributed by Sam007_
JavaScript
function maxSubArraySum(arr) {
    let maxSoFar = -Infinity;
    let maxEndingHere = 0;

    for (let i = 0; i < arr.length; i++) {
        maxEndingHere += arr[i];

        // Use Math.max to find the maximum 
        // of maxSoFar and maxEndingHere
        maxSoFar = Math.max(maxSoFar, maxEndingHere);

        // Use Math.max to reset maxEndingHere
        // to 0 if it becomes negative
        maxEndingHere = Math.max(maxEndingHere, 0);
    }

    return maxSoFar;
}

// Driver code
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
console.log("Maximum contiguous sum is " + 
                        maxSubArraySum(arr));
PHP
<?php
// PHP program to print largest
// contiguous array sum

function maxSubArraySum($a, $size)
{
    $max_so_far = PHP_INT_MIN; 
    $max_ending_here = 0;

    for ($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;
}

// Driver code
$a = array(-2, -3, 4, -1,
           -2, 1, 5, -3);
$n = count($a);
$max_sum = maxSubArraySum($a, $n);
echo "Maximum contiguous sum is " , 
                          $max_sum;

// This code is contributed by anuj_67.
?>

Output
Maximum contiguous sum is 7

Time Complexity: O(N)
Auxiliary Space: O(1)

Illustration:

Lets take the example: {-2, -3, 4, -1, -2, 1, 5, -3}

For i=0,  a[0] =  -2

  • max_ending_here = max_ending_here + (-2)
  • Set max_ending_here = 0 because max_ending_here < 0
  • and set max_so_far = -2

For i=1,  a[1] =  -3

  • max_ending_here = max_ending_here + (-3)
  • Since max_ending_here = -3 and max_so_far = -2, max_so_far will remain -2
  • Set max_ending_here = 0 because max_ending_here < 0

For i=2,  a[2] =  4

  • max_ending_here = max_ending_here + (4)
  • max_ending_here = 4
  • max_so_far is updated to 4 because max_ending_here greater than max_so_far which was -2 till now

For i=3,  a[3] =  -1

  • max_ending_here = max_ending_here + (-1)
  • max_ending_here = 3

For i=4,  a[4] =  -2

  • max_ending_here = max_ending_here + (-2)
  • max_ending_here = 1

For i=5,  a[5] =  1

  • max_ending_here = max_ending_here + (1)
  • max_ending_here = 2

For i=6,  a[6] =  5

  • max_ending_here = max_ending_here + (5)
  • max_ending_here =
  • max_so_far is updated to 7 because max_ending_here is greater than max_so_far

For i=7,  a[7] =  -3

  • max_ending_here = max_ending_here + (-3)
  • max_ending_here = 4

Print the Max Sum Subarray:

To print the subarray with the maximum sum the idea is to maintain start index of maximum_sum_ending_here at current index so that whenever maximum_sum_so_far is updated with maximum_sum_ending_here then start index and end index of subarray can be updated with start and current index.

Follow the below steps to implement the idea:

  • Initialize the variables s, start, and end with 0 and max_so_far = INT_MIN and max_ending_here = 0
  • Run a for loop from 0 to N-1 and for each index i: 
    • Add the arr[i] to max_ending_here.
    • If max_so_far is less than max_ending_here then update max_so_far to max_ending_here and update start to s and end to i .
    • If max_ending_here < 0 then update max_ending_here = 0 and s with i+1.
  • Print values from index start to end.

Below is the Implementation of above approach:

C++
#include <climits>
#include <iostream>
#include <vector>
using namespace std;

void maxSubArraySum(const vector<int>& a) {
    int max_so_far = INT_MIN, max_ending_here = 0,
        start = 0, end = 0, s = 0;

    for (int i = 0; i < a.size(); i++) {
        max_ending_here += a[i];

        // If max_so_far is less than max_ending_here, 
        // update max_so_far
        if (max_so_far < max_ending_here) {
            max_so_far = max_ending_here;
            start = s;
            end = i;
        }

        // If max_ending_here becomes negative, 
        // reset it to 0 and update s
        if (max_ending_here < 0) {
            max_ending_here = 0;
            s = i + 1;
        }
    }

    // Print the maximum sum and the start 
    // and end indices
    cout << "Maximum contiguous sum is " 
         << max_so_far << endl;
    cout << "Starting index " << start << endl
         << "Ending index " << end << endl;
}

/* Driver program to test maxSubArraySum */
int main() {
    vector<int> a = { -2, -3, 4, -1, -2, 1, 5, -3 };
    maxSubArraySum(a);
    return 0;
}
C
#include <stdio.h>
#include <limits.h>

void maxSubArraySum(int a[], int n) {
    int max_so_far = INT_MIN, max_ending_here = 0,
        start = 0, end = 0, s = 0;

    for (int i = 0; i < n; i++) {
        max_ending_here += a[i];

        // If max_so_far is less than max_ending_here, 
        // update max_so_far
        if (max_so_far < max_ending_here) {
            max_so_far = max_ending_here;
            start = s;
            end = i;
        }

        // If max_ending_here becomes negative, 
        // reset it to 0 and update s
        if (max_ending_here < 0) {
            max_ending_here = 0;
            s = i + 1;
        }
    }

    // Print the maximum sum and the start 
    // and end indices
    printf("Maximum contiguous sum is %d\n",
                               max_so_far);
    printf("Starting index %d\n", start);
    printf("Ending index %d\n", end);
}

/* Driver program to test maxSubArraySum */
int main() {
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    int n = sizeof(a) / sizeof(a[0]);
    maxSubArraySum(a, n);
    return 0;
}
Java
// Java program to print largest
// contiguous array sum
import java.io.*;
import java.util.*;
class GFG {

    static void maxSubArraySum(int a[], int size)
    {
        int max_so_far = Integer.MIN_VALUE,
            max_ending_here = 0, start = 0, end = 0, s = 0;

        for (int i = 0; i < size; i++) {
            max_ending_here += a[i];

            if (max_so_far < max_ending_here) {
                max_so_far = max_ending_here;
                start = s;
                end = i;
            }

            if (max_ending_here < 0) {
                max_ending_here = 0;
                s = i + 1;
            }
        }
        System.out.println("Maximum contiguous sum is "
                           + max_so_far);
        System.out.println("Starting index " + start);
        System.out.println("Ending index " + end);
    }

    // Driver code
    public static void main(String[] args)
    {
        int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
        int n = a.length;
        maxSubArraySum(a, n);
    }
}

// This code is contributed by  prerna saini
Python
# Python program to print largest contiguous array sum

from sys import maxsize

# Function to find the maximum contiguous subarray
# and print its starting and end index


def maxSubArraySum(a, size):

    max_so_far = -maxsize - 1
    max_ending_here = 0
    start = 0
    end = 0
    s = 0

    for i in range(0, size):

        max_ending_here += a[i]

        if max_so_far < max_ending_here:
            max_so_far = max_ending_here
            start = s
            end = i

        if max_ending_here < 0:
            max_ending_here = 0
            s = i+1

    print("Maximum contiguous sum is %d" % (max_so_far))
    print("Starting Index %d" % (start))
    print("Ending Index %d" % (end))


# Driver program to test maxSubArraySum
a = [-2, -3, 4, -1, -2, 1, 5, -3]
maxSubArraySum(a, len(a))
C#
// C# program to print largest
// contiguous array sum
using System;

class GFG {
    static void maxSubArraySum(int[] a, int size)
    {
        int max_so_far = int.MinValue, max_ending_here = 0,
            start = 0, end = 0, s = 0;

        for (int i = 0; i < size; i++) {
            max_ending_here += a[i];

            if (max_so_far < max_ending_here) {
                max_so_far = max_ending_here;
                start = s;
                end = i;
            }

            if (max_ending_here < 0) {
                max_ending_here = 0;
                s = i + 1;
            }
        }
        Console.WriteLine("Maximum contiguous "
                          + "sum is " + max_so_far);
        Console.WriteLine("Starting index " + start);
        Console.WriteLine("Ending index " + end);
    }

    // Driver code
    public static void Main()
    {
        int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 };
        int n = a.Length;
        maxSubArraySum(a, n);
    }
}

// This code is contributed
// by anuj_67.
JavaScript
function maxSubArraySum(arr) {
    let maxSoFar = -Infinity, maxEndingHere = 0,
        start = 0, end = 0, s = 0;

    for (let i = 0; i < arr.length; i++) {
        maxEndingHere += arr[i];

        // If maxSoFar is less than maxEndingHere, 
        // update maxSoFar
        if (maxSoFar < maxEndingHere) {
            maxSoFar = maxEndingHere;
            start = s;
            end = i;
        }

        // If maxEndingHere becomes negative, 
        // reset it to 0 and update s
        if (maxEndingHere < 0) {
            maxEndingHere = 0;
            s = i + 1;
        }
    }

    // Print the maximum sum and the start and end indices
    console.log("Maximum contiguous sum is " + maxSoFar);
    console.log("Starting index " + start);
    console.log("Ending index " + end);
}

// Driver code to test maxSubArraySum
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
maxSubArraySum(arr);
PHP
<?php 
// PHP program to print largest 
// contiguous array sum

function maxSubArraySum($a, $size)
{
    $max_so_far = PHP_INT_MIN;
    $max_ending_here = 0;
    $start = 0;
    $end = 0;
    $s = 0;

    for ($i = 0; $i < $size; $i++)
    {
        $max_ending_here += $a[$i];

        if ($max_so_far < $max_ending_here)
        {
            $max_so_far = $max_ending_here;
            $start = $s;
            $end = $i;
        }

        if ($max_ending_here < 0)
        {
            $max_ending_here = 0;
            $s = $i + 1;
        }
    }
    echo "Maximum contiguous sum is ".
                     $max_so_far."\n";
    echo "Starting index ". $start . "\n".
            "Ending index " . $end . "\n";
}

// Driver Code
$a = array(-2, -3, 4, -1, -2, 1, 5, -3);
$n = sizeof($a);
maxSubArraySum($a, $n);

// This code is contributed
// by ChitraNayal
?>

Output
Maximum contiguous sum is 7
Starting index 2
Ending index 6

Time Complexity: O(n)
Auxiliary Space: O(1)

Using Dynamic Programming:

For each index i, DP[i] stores the maximum possible Largest Sum Contiguous Subarray ending at index i, and therefore we can calculate DP[i] using the mentioned state transition:

  • DP[i] = max(DP[i-1] + arr[i] , arr[i] )

Below is the implementation:

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

void maxSubArraySum(const vector<int>& a) {
    int n = a.size();
    vector<int> dp(n, 0);
    dp[0] = a[0];
    int ans = dp[0];
    
    for (int i = 1; i < n; i++) {
        dp[i] = max(a[i], a[i] + dp[i - 1]);
        ans = max(ans, dp[i]);
    }
    
    cout << ans;
}

/* Driver program to test maxSubArraySum */
int main() {
    vector<int> a = { -2, -3, 4, -1, -2, 1, 5, -3 };
    maxSubArraySum(a);
    return 0;
}
C
#include <stdio.h>
#include <limits.h>

int max(int x, int y) {return (x > y) ? x : y;}

void maxSubArraySum(int a[], int n) {
    int dp[n];
    dp[0] = a[0];
    int ans = dp[0];

    for (int i = 1; i < n; i++) {
        dp[i] = max(a[i], a[i] + dp[i - 1]);
        ans = max(ans, dp[i]);
    }

    printf("%d\n", ans);
}

/* Driver program to test maxSubArraySum */
int main() {
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    int n = sizeof(a) / sizeof(a[0]);
    maxSubArraySum(a, n);
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    // Function to find the largest contiguous array sum
    public static void maxSubArraySum(int[] a) {
        int size = a.length;
        int[] dp = new int[size]; // Create an array to store intermediate results
        dp[0] = a[0]; // Initialize the first element of the intermediate array with the first element of the input array
        int ans = dp[0]; // Initialize the answer with the first element of the intermediate array
        for (int i = 1; i < size; i++) {
            // Calculate the maximum of the current element and the sum of the current element and the previous result
            dp[i] = Math.max(a[i], a[i] + dp[i - 1]);
            // Update the answer with the maximum value encountered so far
            ans = Math.max(ans, dp[i]);
        }
        // Print the maximum contiguous array sum
        System.out.println(ans);
    }

    public static void main(String[] args) {
        int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 };
        maxSubArraySum(a); // Call the function to find and print the maximum contiguous array sum
    }
}
// This code is contributed by shivamgupta310570
Python
# Python program for the above approach

def max_sub_array_sum(a, size):
    # Create a list to store intermediate results
    dp = [0] * size

    # Initialize the first element of the list with the first element of the array
    dp[0] = a[0]

    # Initialize the answer with the first element of the array
    ans = dp[0]

    # Loop through the array starting from the second element
    for i in range(1, size):
        # Choose the maximum value between the current element and the sum of the current element
        # and the previous maximum sum (stored in dp[i - 1])
        dp[i] = max(a[i], a[i] + dp[i - 1])

        # Update the overall maximum sum
        ans = max(ans, dp[i])

    # Print the maximum contiguous subarray sum
    print(ans)

# Driver program to test max_sub_array_sum
if __name__ == "__main__":
    # Sample array
    a = [-2, -3, 4, -1, -2, 1, 5, -3]

    # Get the length of the array
    n = len(a)

    # Call the function to find the maximum contiguous subarray sum
    max_sub_array_sum(a, n)

# This code is contributed by Susobhan Akhuli
C#
using System;

class MaxSubArraySum {
    // Function to find and print the maximum sum of a
    // subarray
    static void FindMaxSubArraySum(int[] arr, int size)
    {
        // Create an array to store the maximum sum of
        // subarrays
        int[] dp = new int[size];

        // Initialize the first element of dp with the first
        // element of arr
        dp[0] = arr[0];

        // Initialize a variable to store the final result
        int ans = dp[0];

        // Iterate through the array to find the maximum sum
        for (int i = 1; i < size; i++) {
            // Calculate the maximum sum ending at the
            // current position
            dp[i] = Math.Max(arr[i], arr[i] + dp[i - 1]);

            // Update the final result with the maximum sum
            // found so far
            ans = Math.Max(ans, dp[i]);
        }

        // Print the maximum sum of the subarray
        Console.WriteLine(ans);
    }

    // Driver program to test FindMaxSubArraySum
    static void Main()
    {
        // Example array
        int[] arr = { -2, -3, 4, -1, -2, 1, 5, -3 };

        // Calculate and print the maximum subarray sum
        FindMaxSubArraySum(arr, arr.Length);
    }
}
JavaScript
function maxSubArraySum(arr) {
    let n = arr.length;
    let dp = new Array(n).fill(0);
    dp[0] = arr[0];
    let ans = dp[0];

    for (let i = 1; i < n; i++) {
        dp[i] = Math.max(arr[i], arr[i] + dp[i - 1]);
        ans = Math.max(ans, dp[i]);
    }

    console.log(ans);
}

// Driver code to test maxSubArraySum
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
maxSubArraySum(arr);

Output
7


Time Complexity: O(n)
Auxiliary Space: O(n)

Practice Problem: 

Given an array of integers (possibly some elements negative), write a C program to find out the *maximum product* possible by multiplying ‘n’ consecutive integers in the array where n ? ARRAY_SIZE. Also, print the starting point of the maximum product subarray.




Similar Reads

3D Kadane's Algorithm
What is Kadane's Algorithm?Kadane's algorithm is a dynamic programming technique used to find the maximum subarray sum within a one-dimensional array. It efficiently computes the maximum sum of a contiguous subarray, and its simplicity and effectiveness make it a popular choice for solving related problems. Idea/Working of Kadane's Algorithm:The id
14 min read
First subarray having sum at least half the maximum sum of any subarray of size K
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum possible sum from any subarray of size K is 16 fr
9 min read
Maximum Subarray Sum using Divide and Conquer algorithm
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 (see highlighted elements). Recommended: Please solve it on “PRACTICE ” first, befo
12 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 min read
Maximum sum subarray having sum less than or equal to given sum
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. Note: Given array contains only non-negative integers. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } sum = 11Output: 10Subarray having maximum sum is { 1, 2, 3, 4 }Input: arr[] = { 2, 4, 6, 8, 10
10 min read
Maximum length of subarray such that all elements are equal in the subarray
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2, 3, 4} Output: 1 Explanation: All identical elemen
5 min read
Maximum sum of K-length subarray with maximum count of distinct prime factors
Given an array arr[] consisting of N positive integers and an integer K, the task is to find the maximum sum of array elements in a subarray having maximum sum of distinct prime factors in each K-length subarray. Note: If there are multiple answers then print the sum of the original subarray having maximum sum. Examples: Input: arr[] = {1, 4, 2, 10
11 min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost
Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation with the cost equal to the sum of elements of the su
11 min read
Maximize the subarray sum after multiplying all elements of any subarray with X
Given an array arr[] of N integers and an integer X. We can choose any sub-array and multiply all its element by X. After multiplication, find the sub-array with the maximum sum. The task is to multiply the sub-array in such a way that the final sub-array sum is maximized. Examples: Input: arr[] = { -3, 8, -2, 1, -6 }, X = -1 Output: 15 Choose the
15+ min read
Find minimum subarray sum for each index i in subarray [i, N-1]
Given an array arr[] of size N, the task is to find the minimum subarray sum in the subarrays [i, N-1] for all i in [0, N-1]. Examples: Input: arr[ ] = {3, -1, -2}Output: -3 -3 -2Explanation: For (i = 1) i.e. {3, -1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 2) i.e. {-1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 3) i
9 min read
Maximize subarray sum by inverting sign of elements of any subarray at most twice
Given an array A of size n, find the maximum subarray sum after applying the given operation at most two times. In one operation, choose any two indices i and j and invert sign of all the elements from index i to index j, i.e, all positive elements in the range i to j become negative and all negative elements become positive. Examples: Input: A[] =
10 min read
Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Count of subarray that does not contain any subarray with sum 0
Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements may not be distinct.Examples: Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not contain any subarray whose elements sum is equal to
11 min read
Maximum subarray sum in O(n) using prefix sum
Given an Array of Positive and Negative Integers, find out the Maximum Subarray Sum in that Array. Examples: Input1 : arr = {-2, -3, 4, -1, -2, 1, 5, -3} Output1 : 7 Input2 : arr = {4, -8, 9, -4, 1, -8, -1, 6} Output2 : 9 Kadane's Algorithm solves this problem using Dynamic Programming approach in linear time. Here is another approach using Dynamic
8 min read
Maximum sum subarray of size K with sum less than X
Given an array arr[] and two integers K and X, the task is to find the maximum sum among all subarrays of size K with the sum less than X. Examples: Input: arr[] = {20, 2, 3, 10, 5}, K = 3, X = 20Output: 18Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, required output is 18. Input: arr[] = {-5, 8, 7, 2, 10
7 min read
Smallest pair of indices with product of subarray co-prime with product of the subarray on the left or right
Given an array arr[] of length N, the task is to find the smallest pair of indices (i, j) such that the product of elements in the subarray arr[i + 1, j - 1] is co-prime with either the product of the subarray arr[0, i] or that of the subarray arr[j, N]. If no such pair exists, the print "-1". Examples: Input: arr[] = {2, 4, 1, 3, 7}Output: (0, 2)E
12 min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Maximum subarray sum in an array created after repeated concatenation
Given an array and a number k, find the largest sum of contiguous array in the modified array which is formed by repeating the given array k times. Examples : Input : arr[] = {-1, 10, 20}, k = 2 Output : 59 After concatenating array twice, we get {-1, 10, 20, -1, 10, 20} which has maximum subarray sum as 59. Input : arr[] = {-1, -2, -3}, k = 3 Outp
6 min read
Maximum Subarray Sum in a given Range
Given an array of n numbers, the task is to answer the following queries: maximumSubarraySum(start, end) : Find the maximum subarray sum in the range from array index 'start' to 'end'. Also see : Range Query With Update Required Examples: Input : arr[] = {1, 3, -4, 5, -2} Query 1: start = 0, end = 4 Query 2: start = 0, end = 2 Output : 5 4 Explanat
15+ min read
Size of The Subarray With Maximum Sum
Given an array arr[] of size N, the task is to find the length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1} Output : Length of the subarray is 2 Explanation : Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2 Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 } Output : Length of the su
10 min read
Maximum Subarray Sum Excluding Certain Elements
Given an array of A of n integers and an array B of m integers find the Maximum Contiguous Subarray Sum of array A such that any element of array B is not present in that subarray. Examples : Input : A = {1, 7, -10, 6, 2}, B = {5, 6, 7, 1} Output : 2 Explanation Since the Maximum Sum Subarray of A is not allowed to have any element that is present
15+ min read
Split array to three subarrays such that sum of first and third subarray is equal and maximum
Given an array of N integers, the task is to print the sum of the first subarray by splitting the array into exactly three subarrays such that the sum of the first and third subarray elements are equal and the maximum. Note: All the elements must belong to a subarray and the subarrays can also be empty. Examples: Input: a[] = {1, 3, 1, 1, 4} Output
13 min read
Maximum sum subarray such that start and end values are same
Given an array of N positive numbers, the task is to find a contiguous subarray (L-R) such that a[L]=a[R] and sum of a[L] + a[L+1] +...+ a[R] is maximum. Examples: Input: arr[] = {1, 3, 2, 2, 3} Output: 10 Subarray [3, 2, 2, 3] starts and ends with 3 and has sum = 10 Input: arr[] = {1, 3, 2, 2, 3} Output: 10 Approach: For every element in the array
6 min read
Maximum subarray sum in array formed by repeating the given array k times
Given an integer k and an integer array arr[] of n elements, the task is to find the largest sub-array sum in the modified array (formed by repeating the given array k times). For example, if arr[] = {1, 2} and k = 3 then the modified array will be {1, 2, 1, 2, 1, 2}. Examples: Input: arr[] = {1, 2}, k = 3 Output: 9 Modified array will be {1, 2, 1,
12 min read
Maximum subarray sum by flipping signs of at most K array elements
Given an array arr[] of N integers and an integer K, The task is to find the maximum sub-array sum by flipping signs of at most K array elements. Examples: Input: arr[] = {-6, 2, -1, -1000, 2}, k = 2 Output: 1009 We can flip the signs of -6 and -1000, to get maximum subarray sum as 1009 Input: arr[] = {-1, -2, -100, -10}, k = 1 Output: 100 We can o
9 min read
Maximum Subarray Sum after inverting at most two elements
Given an array arr[] of integer elements, the task is to find maximum possible sub-array sum after changing the signs of at most two elements.Examples: Input: arr[] = {-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6} Output: 61 We can get 61 from index 0 to 10 by changing the sign of elements at 4th and 7th indices i.e. -8 and -9. We could have chosen -5 and
11 min read
Maximize product of subarray sum with its maximum element
Given an array arr[] consisting of N positive integers, the task is to find the maximum product of the subarray sum with the maximum element of that subarray. Examples: Input: arr[] = {2, -3, 8, -2, 5}Output: 88Explanation:The required maximum product can be obtained using subarray {8, -2, 5}Therefore, maximum product = (8 + (-2) + 5) * (8) = 88. I
8 min read
Maximum circular subarray sum of size K
Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also). Examples: Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3 Output: max circular sum = 32 start index = 9 end index = 1 Explanation: Maximum Sum = 10 + 18 + 4 = 32 Input: arr =
6 min read
Maximum sum subarray after altering the array
Given an array arr[] of size N. The task is to find the maximum subarray sum possible after performing the given operation at most once. In a single operation, you can choose any index i and either the subarray arr[0...i] or the subarray arr[i...N-1] can be reversed. Examples: Input: arr[] = {3, 4, -2, 1, 3} Output: 11 After reversing arr[0...2], a
15+ min read
Minimum size Subarray with maximum sum in non-increasing order
Given an array arr, the task is to find a subarray of the array elements whose sum is strictly greater than the rest of the elements. The size of the subarray should be minimum and the sum should be maximum and it must be in non-increasing order.Examples: Input: arr = [7, 6, 13, 12, 11] Output: 13 12 Explanation: The subarray [13, 12] and [13, 11]
6 min read