We are asked: "Write an algorithm to solve the maximum subarray problem in O(n) time." So we need to present an algorithm, likely Kadane's algorithm. We should write it in a clear, step-by-step manner, maybe in pseudocode, and explain it.
We should produce a final answer: the algorithm description, pseudocode, and maybe a brief explanation of correctness and complexity.
We must follow instructions: The assistant should provide a helpful, detailed response. We need to output the algorithm.
I'll produce a solution with:
Problem definition: Given an array of integers (could be negative), find the contiguous subarray with the largest sum.
Kadane's algorithm: iterate through array, keep track of current maximum sum ending at each position, and overall maximum.
Pseudocode:
function maxSubarray(A):
max_ending_here = A[0]
max_so_far = A[0]
for i from 1 to n-1:
max_ending_here = max(A[i], max_ending_here + A[i])
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
If array can be empty, handle separately.
Complexity: O(n) time, O(1) extra space.
We can also discuss handling all negative numbers.
We'll produce a final answer with explanation and pseudocode.
Let's write the answer.
The maximum subarray problem is to find the contiguous subarray within a one-dimensional array of numbers that has the largest sum. Kadane's algorithm solves this in O(n) time using dynamic programming. The key idea is to iterate through the array, maintaining the maximum sum of a subarray ending at the current position and the overall maximum sum encountered so far.
Algorithm (Kadane's Algorithm)
Initialize two variables:
max_ending_here = first element of the array (this stores the maximum sum of a subarray ending at the current index).
max_so_far = first element (this stores the overall maximum sum found).
For each subsequent element x in the array (starting from the second element):
Update max_ending_here to be the maximum of x itself or max_ending_here + x. This decides whether to start a new subarray at the current element or extend the previous subarray.
Update max_so_far to be the maximum of max_so_far and max_ending_here.
After processing all elements, max_so_far holds the maximum subarray sum.
If the array may be empty, handle that case separately (e.g., return 0 or an appropriate sentinel).
Pseudocode
code
function maxSubarray(A):
if A.length == 0:
return 0 // or throw exception / handle as needed
max_ending_here = A[0]
max_so_far = A[0]
for i from 1 to A.length - 1:
max_ending_here = max(A[i], max_ending_here + A[i])
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
All negative numbers: The algorithm correctly returns the least negative (i.e., the maximum element) because max_ending_here will never become positive, and max_so_far will capture the highest single element.
Single element: Works trivially.
Kadane's algorithm is the standard optimal solution for the maximum subarray problem.