Find minimum subarray sum for each index i in subarray [i, N-1]
Last Updated :
29 Dec, 2022
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 -2
Explanation:
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.e. {-2}, the minimum subarray sum is -2 for {-2}.
Input: arr[ ] = {5, -3, -2, 9, 4}
Output: -5 -5 -2 4 4
Approach: The problem can be solved by using the standard Kadane's algorithm for maximum subarray sum. Follow the steps below to solve this problem:
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Kadane's Algorithm to find max
// sum subarray
int kadane(int arr[], int start, int end)
{
int currMax = arr[start];
int maxSoFar = arr[start];
// Iterating from start to end
for (int i = start + 1; i < end + 1; i++) {
currMax = max(arr[i], arr[i] + currMax);
maxSoFar = max(maxSoFar, currMax);
}
// Returning maximum sum
return maxSoFar;
}
// Function to find the minimum subarray
// sum for each suffix
void minSubarraySum(int arr[], int n)
{
// Inverting all the elements of
// array arr[].
for (int i = 0; i < n; i++) {
arr[i] = -arr[i];
}
// Finding the result for each
// subarray
for (int i = 0; i < n; i++) {
// Finding the max subarray sum
int result = kadane(arr, i, n - 1);
// Inverting the result
result = -result;
// Print the result
cout << result << " ";
}
}
// Driver code
int main()
{
// Given Input
int n = 5;
int arr[] = { 5, -3, -2, 9, 4 };
// Function Call
minSubarraySum(arr, n);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG{
// Kadane's Algorithm to find max
// sum subarray
static int kadane(int arr[], int start, int end)
{
int currMax = arr[start];
int maxSoFar = arr[start];
// Iterating from start to end
for(int i = start + 1; i < end + 1; i++)
{
currMax = Math.max(arr[i], arr[i] + currMax);
maxSoFar = Math.max(maxSoFar, currMax);
}
// Returning maximum sum
return maxSoFar;
}
// Function to find the minimum subarray
// sum for each suffix
static void minSubarraySum(int arr[], int n)
{
// Inverting all the elements of
// array arr[].
for(int i = 0; i < n; i++)
{
arr[i] = -arr[i];
}
// Finding the result for each
// subarray
for(int i = 0; i < n; i++)
{
// Finding the max subarray sum
int result = kadane(arr, i, n - 1);
// Inverting the result
result = -result;
// Print the result
System.out.print(result + " ");
}
}
// Driver code
public static void main(String[] args)
{
// Given Input
int n = 5;
int arr[] = { 5, -3, -2, 9, 4 };
// Function Call
minSubarraySum(arr, n);
}
}
// This code is contributed by Potta Lokesh
Python3
# Python3 program for the above approach
# Kadane's Algorithm to find max
# sum subarray
def kadane(arr, start, end):
currMax = arr[start]
maxSoFar = arr[start]
# Iterating from start to end
for i in range(start + 1,end + 1, 1):
currMax = max(arr[i], arr[i] + currMax)
maxSoFar = max(maxSoFar, currMax)
# Returning maximum sum
return maxSoFar
# Function to find the minimum subarray
# sum for each suffix
def minSubarraySum(arr, n):
# Inverting all the elements of
# array arr[].
for i in range(n):
arr[i] = -arr[i]
# Finding the result for each
# subarray
for i in range(n):
# Finding the max subarray sum
result = kadane(arr, i, n - 1)
# Inverting the result
result = -result
# Print the result
print(result, end = " ")
# Driver code
if __name__ == '__main__':
# Given Input
n = 5
arr = [ 5, -3, -2, 9, 4 ]
# Function Call
minSubarraySum(arr, n)
# This code is contributed by SURENDRA_GANGWAR
C#
// C# program for the above approach
using System;
class GFG{
// Kadane's Algorithm to find max
// sum subarray
static int kadane(int []arr, int start, int end)
{
int currMax = arr[start];
int maxSoFar = arr[start];
// Iterating from start to end
for(int i = start + 1; i < end + 1; i++)
{
currMax = Math.Max(arr[i], arr[i] + currMax);
maxSoFar = Math.Max(maxSoFar, currMax);
}
// Returning maximum sum
return maxSoFar;
}
// Function to find the minimum subarray
// sum for each suffix
static void minSubarraySum(int []arr, int n)
{
// Inverting all the elements of
// array arr[].
for(int i = 0; i < n; i++)
{
arr[i] = -arr[i];
}
// Finding the result for each
// subarray
for(int i = 0; i < n; i++)
{
// Finding the max subarray sum
int result = kadane(arr, i, n - 1);
// Inverting the result
result = -result;
// Print the result
Console.Write(result + " ");
}
}
// Driver code
public static void Main(String[] args)
{
// Given Input
int n = 5;
int []arr = { 5, -3, -2, 9, 4 };
// Function Call
minSubarraySum(arr, n);
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// Javascript program for the above approach
// Kadane's Algorithm to find max
// sum subarray
function kadane(arr, start, end)
{
let currMax = arr[start];
let maxSoFar = arr[start];
// Iterating from start to end
for(let i = start + 1; i < end + 1; i++)
{
currMax = Math.max(arr[i], arr[i] + currMax);
maxSoFar = Math.max(maxSoFar, currMax);
}
// Returning maximum sum
return maxSoFar;
}
// Function to find the minimum subarray
// sum for each suffix
function minSubarraySum(arr, n)
{
// Inverting all the elements of
// array arr[].
for(let i = 0; i < n; i++)
{
arr[i] = -arr[i];
}
// Finding the result for each
// subarray
for(let i = 0; i < n; i++)
{
// Finding the max subarray sum
let result = kadane(arr, i, n - 1);
// Inverting the result
result = -result;
// Print the result
document.write(result + " ");
}
}
// Driver code
// Given Input
let n = 5;
let arr = [ 5, -3, -2, 9, 4 ];
// Function Call
minSubarraySum(arr, n);
// This code is contributed by gfgking
</script>
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Efficient Approach: The repetitive process of finding the maximum subarray sum using Kadane's can be optimized further by traversing the array from the back and storing the maximum negative sum till that point from the end.
Below is the code implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void minSubarraySum(int arr[], int n)
{
vector<int> res(n);
for (int i = 0; i < n; i++)
arr[i] *= -1;
int sum = 0;
int maxSum = INT_MIN;
for (int i = n - 1; i >= 0; i--) {
sum += arr[i];
maxSum = max(sum, maxSum);
// Store result for [i,n-1]
res[i] = -maxSum;
if (sum < 0)
sum = 0;
}
for (int i : res)
cout << i << " ";
}
int main()
{
int n = 5;
int arr[] = { 5, -3, -2, 9, 4 };
// Function Call
minSubarraySum(arr, n);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
class GFG {
public static void minSubarraySum(int arr[], int n)
{
int[] res = new int[n];
for (int i = 0; i < n; i++)
arr[i] *= -1;
int sum = 0;
int maxSum = Integer.MIN_VALUE;
for (int i = n - 1; i >= 0; i--) {
sum += arr[i];
maxSum = Math.max(sum, maxSum);
// Store result for [i,n-1]
res[i] = -maxSum;
if (sum < 0)
sum = 0;
}
for (int i : res)
System.out.print(i + " ");
}
// Driver Code
public static void main(String[] args)
{
int n = 5;
int arr[] = { 5, -3, -2, 9, 4 };
// Function Call
minSubarraySum(arr, n);
}
}
// This code is contributed by aarohirai2616.
Python3
def minSubarraySum(arr, n):
res = [0]*n
for i in range(0, n):
arr[i] *= -1
suma = 0
maxSum = -9223372036854775808
i = n - 1
while(i >= 0):
suma += arr[i]
maxSum = max(suma, maxSum)
# Store result for [i,n-1]
res[i] = -maxSum
if (suma < 0):
suma = 0
i = i-1
for i in range(0, n):
print(res[i], end=" ")
# Driver code
n = 5
arr = [5, -3, -2, 9, 4]
# Function Call
minSubarraySum(arr, n)
# This code is contributed by aarohirai2616.
C#
// C# code to implement the approach
using System;
public class GFG {
public static void minSubarraySum(int[] arr, int n)
{
int[] res = new int[n];
for (int i = 0; i < n; i++)
arr[i] *= -1;
int sum = 0;
int maxSum = Int32.MinValue;
for (int i = n - 1; i >= 0; i--) {
sum += arr[i];
maxSum = Math.Max(sum, maxSum);
// Store result for [i,n-1]
res[i] = -maxSum;
if (sum < 0)
sum = 0;
}
for (int i = 0; i < n; i++) {
Console.Write(res[i] + " ");
}
}
static public void Main()
{
// Code
int n = 5;
int[] arr = { 5, -3, -2, 9, 4 };
// Function Call
minSubarraySum(arr, n);
}
}
// This code is contributed by lokeshmvs21.
JavaScript
function minSubarraySum(arr, n)
{
let res = [];
for(let i=0;i<n;i++)
{
res.push(0);
}
for (let i = 0; i < n; i++)
arr[i] *= -1;
let sum = 0;
let maxSum = -2147483647 - 1;
for (let i = n - 1; i >= 0; i--) {
sum += arr[i];
maxSum = Math.max(sum, maxSum);
// Store result for [i,n-1]
res[i] = -1*maxSum;
if (sum < 0)
sum = 0;
}
console.log(res);
}
let n = 5;
let arr = [ 5, -3, -2, 9, 4 ];
// Function Call
minSubarraySum(arr, n);
// This code is contributed by akashish__
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read