![]() |
VOOZH | about |
Given an array containing n integers. The problem is to find the sum of the elements of the contiguous subarray having the smallest(minimum) sum.
Examples:
Input: arr[] = {3, -4, 2, -3, -1, 7, -5}
Output: -6
Explanation: Subarray with minimum sum is {-4, 2, -3, -1} = -6Input: arr = {2, 6, 8, 1, 4}
Output: 1
Explanation: Subarray with minimum sum is {1} = 1
Consider all the contiguous subarrays of different sizes and find their sum. The subarray having the smallest(minimum) sum is the required answer.
-6
It is a variation to the problem of finding the largest sum contiguous subarray based on the idea of Kadane’s algorithm.
The idea is to traverse over the array from left to right and for each element, find the minimum sum sum among all subarrays ending at that element. The result will be the maximum of all these values.
But, the main issue is how to calculate minimum sum among all the subarrays ending at an element in O(n) time?
To calculate the minimum sum of subarray ending at current element, say min_ending_here, we can use the minimum sum ending at the previous element. So for any element, we have two choices:
- Choice 1: Extend the minimum sum subarray ending at the previous element by adding the current element to it. If the minimum subarray sum ending at the previous index is negative, then it is always better to extend the subarray.
- Choice 2: Start a new subarray starting from the current element. If the minimum subarray sum ending at the previous index is positive, it is always better to start a new subarray from the current element.
-6