The Wayback Machine - https://web.archive.org/web/20210711212809/https://www.geeksforgeeks.org/find-minimum-subarray-sum-for-each-index-i-in-subarray-i-n-1/
Skip to content
Related Articles

Related Articles

Improve Article
Find minimum subarray sum for each index i in subarray [i, N-1]
  • Last Updated : 10 Jul, 2021

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 sart 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;
}
Output
-5 -5 -2 4 4 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :