710028. Smallest sum contiguous subarray
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:
- Create an array
dpof sizen, wherenis the length of the input array. - Initialize all elements in
dpto the corresponding elements in the input array. - 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].
- If we include the current element, the sum will be
- Update
dp[i]with the minimum of these two sums. - Find the smallest sum by iterating through
dpand finding the minimum value.
Time complexity: O(n) Space complexity: O(n)
Optimized Solutions
Java
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;
}
}