The Maximum Subarray Sum problem requires finding a contiguous subarray within an array of integers that yields the maximum possible sum. A subarray is a continuous segment of the array, meaning elements must be adjacent (e.g., in [-2, 1, -3, 4, -1], [1, -3, 4] is a subarray, but [1, 4] is not).
n typically ranges from 1 to 10⁵, and elements can be large, requiring long for sums to avoid overflow.For the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the subarray [4, -1, 2, 1] has the maximum sum of 6. For an all-negative array like [-4, -2, -3], the maximum sum is -2 (largest single element) or 0 (empty subarray, depending on the problem).
This problem is a staple in coding interviews (e.g., LeetCode #53) due to its emphasis on optimization and dynamic programming principles. It has applications in financial analysis (e.g., maximum profit from stock prices), signal processing, and data segmentation.
A subarray is a contiguous portion of an array. Apna College emphasizes this concept by illustrating all possible subarrays and their counts.
n, the number of subarrays is calculated as:[\text{Total Subarrays} = \frac{n \cdot (n+1)}{2}]For example, an array of size 5 has (\frac{5 \cdot 6}{2} = 15) subarrays.i from 0 to n-1.j from i to n-1.i to j.public class PrintSubarrays {
public static void printSubarrays(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) { // Start index
for (int j = i; j < n; j++) { // End index
// Print subarray from i to j
for (int k = i; k <= j; k++) {
System.out.print(arr[k] + " ");
}
System.out.println();
}
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
printSubarrays(arr);
// Output: All 15 subarrays (e.g., [1], [1, 2], [1, 2, 3], ..., [1, 2, 3, 4, 5])
}
}