Sponsored
Sponsored
This approach uses Kadane's Algorithm, which is an efficient way to find the maximum subarray sum in linear time.
We iterate through the array, keeping track of the maximum sum of the subarray ending at the current position and the overall maximum sum found so far.
The algorithm maintains two variables: current_max, which is the maximum sum of the subarray that ends at the current index, and global_max, which is the maximum sum found so far.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), because we are using a constant amount of extra space.
1public class MaxSubArray {
2 public int maxSubArray(int[] nums) {
3 int currentMax = nums[0];
4 int globalMax = nums[0];
5
6 for (int i = 1; i < nums.length; i++) {
7 currentMax = Math.max(nums[i], currentMax + nums[i]);
8 if (currentMax > globalMax) {
9 globalMax = currentMax;
10 }
11 }
12
13 return globalMax;
14 }
15
16 public static void main(String[] args) {
17 MaxSubArray solution = new MaxSubArray();
18 int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
19 System.out.println("Maximum subarray sum is " + solution.maxSubArray(nums));
20 }
21}This Java code implements Kadane's Algorithm, updating currentMax and globalMax during the iteration.
This approach splits the array into two halves and finds the maximum subarray sum for each half recursively. It also considers the possibility of the maximum subarray crossing the midpoint.
To find the maximum crossing subarray, we begin at the midpoint and expand outward to the left and right, keeping track of the maximum sum.
This approach effectively divides the problem into smaller subproblems and conquers each independently, then combines their results.
Time Complexity: O(n log n)
Space Complexity: O(log n) for the recursion stack
1
This Python code uses a divide and conquer strategy, recursively calculating maximum subarray sums for the left, right, and crossing sections of the array. It combines these results to find the overall maximum subarray sum.