
Originally published byDev.to
The Problem
Given an array of integers.
The Task is to find the maximum sum of a contiguous subarray.
Example:
Input: [2, 3, -8, 7, -1, 2, 3]
Output: 11
Idea
If your current sum becomes negative:
Drop it immediately
Start fresh from next element
Algorithm Logic
At each index:
current_sum = max(arr[i], current_sum + arr[i])
max_sum = max(max_sum, current_sum)
Example
Array:
[2, 3, -8, 7, -1, 2, 3]
Step-by-step:
- Start with 2 β current = 2
- Add 3 β current = 5
- Add -8 β current = -3 β (bad β drop)
- Start fresh at 7 β current = 7
- Add -1 β current = 6
- Add 2 β current = 8
- Add 3 β current = 11 β
answer = 11
Python Code
class Solution:
def maxSubarraySum(self, arr):
max_sum = arr[0]
current_sum = arr[0]
for i in range(1, len(arr)):
current_sum = max(arr[i], current_sum + arr[i])
max_sum = max(max_sum, current_sum)
return max_sum
All numbers are negative:
[-2, -4]
Answer = -2 (not 0)
max_sum = arr[0]
πΊπΈ
More news from United StatesUnited States
NORTH AMERICA
Related News
Jeff Bezos Seeking $100 Billion to Buy Manufacturing Companies, 'Transform' Them With AI
9h ago
Firefox Announces Built-In VPN and Other New Features - and Introduces Its New Mascot
9h ago
Can Private Space Companies Replace the ISS Before 2030?
9h ago
Juicier Steaks Soon? The UK Approves Testing of Gene-Edited Cow Feed
9h ago
White House Unveils National AI Policy Framework To Limit State Power
9h ago

