710028. Smallest sum contiguous subarray

Medium

Here is the Markdown blog post for the problem "Smallest sum contiguous subarray":

Smallest sum contiguous subarray Slug: smallest-sum-contiguous-subarray Difficulty: Medium Id: 710028 Topic Tags: Arrays, Dynamic Programming, Data Structures, Algorithms Company Tags: None

Summary

The problem is to find the smallest sum of a contiguous subarray within an array. The array contains integers and we need to find the smallest possible sum for any contiguous subarray (i.e., a subarray that is not necessarily contiguous). This problem involves dynamic programming, arrays, and algorithms.

Detailed Explanation

To solve this problem, we can use a dynamic programming approach. We will create an array dp where dp[i] represents the smallest sum of a contiguous subarray ending at index i. Initially, all elements in dp are set to the corresponding elements in the input array.

We then iterate through the array from left to right and for each element, we calculate the minimum sum by considering two options: either the current element is included in the subarray or it's not. If we include the current element, the sum will be dp[i-1] + arr[i]. If we don't include the current element, the sum will simply be dp[i-1].

We update dp[i] with the minimum of these two sums.

Finally, we find the smallest sum by iterating through dp and finding the minimum value. This value represents the smallest sum of a contiguous subarray in the input array.

Here's the step-by-step breakdown:

  1. Create an array dp of size n, where n is the length of the input array.
  2. Initialize all elements in dp to the corresponding elements in the input array.
  3. Iterate through the array from left to right and for each element, calculate the minimum sum by considering two options:
    • If we include the current element, the sum will be dp[i-1] + arr[i].
    • If we don't include the current element, the sum will simply be dp[i-1].
  4. Update dp[i] with the minimum of these two sums.
  5. Find the smallest sum by iterating through dp and finding the minimum value.

Time complexity: O(n) Space complexity: O(n)

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static int smallestSumContiguousSubarray(int[] arr) {
        int n = arr.length;
        int[] dp = new int[n];
        int minSum = Integer.MAX_VALUE;

        for (int i = 0; i < n; i++) {
            if (i == 0) {
                dp[i] = arr[i];
            } else {
                dp[i] = Math.min(dp[i-1] + arr[i], arr[i]);
            }

            minSum = Math.min(minSum, dp[i]);
        }

        return minSum;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.