Problem Definition: Maximum Subarray Sum

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).

Key Points:

Example:

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).

Relevance:

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.


Understanding Subarrays

A subarray is a contiguous portion of an array. Apna College emphasizes this concept by illustrating all possible subarrays and their counts.

Key Concepts:

Java Implementation (Printing All Subarrays):

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])
    }
}