We use Kadane's Algorithm. The idea is to maintain a current_sum that gathers the sum of the subarray and a max_sum that tracks the maximum found so far. If current_sum becomes negative, we reset it to zero because a negative sum will only decrease the sum of any subsequent subarray.
- Initialize
max_so_farto a very small number andcurrent_maxto 0. - Iterate through each
profitin theprofitsarray. - Add
profittocurrent_max. - If
current_max > max_so_far, updatemax_so_far. - If
current_max < 0, resetcurrent_maxto 0. - Return
max_so_far.
- Time Complexity: O(N), where N is the length of the array.
- Space Complexity: O(1), as we only use a few variables.
def max_subarray_sum(profits):
# Handle edge case where all numbers might be negative
max_so_far = float('-inf')
current_max = 0
for profit in profits:
current_max += profit
if current_max > max_so_far:
max_so_far = current_max
if current_max < 0:
current_max = 0
return max_so_far