Before we tackle the legendary Kadane's Algorithm (Maximum Subarray), we need to understand a beautifully simple concept: the running sum.
Think of your bank account. Every deposit or withdrawal doesn't stand alone — it adds to your running balance. If you deposited $100, then $50, then $25, your balance after each transaction is $100, $150, $175. That's a running sum! 🏦
Running sum (also called cumulative sum): each element in the result is the sum of all elements from the start up to and including that position.
Given [1, 2, 3, 4]:
1 → result is 11 + 2 = 3 → result is 31 + 2 + 3 = 6 → result is 61 + 2 + 3 + 4 = 10 → result is 10So running_sum([1, 2, 3, 4]) returns [1, 3, 6, 10]. Each number "remembers" everything that came before it. 🧠
The trick? You don't need to re-add everything from scratch each time. Just keep a total variable and keep adding to it as you go:
Why does this matter? Kadane's algorithm is basically a running sum with one twist — at each step you decide: "Should I extend my running sum, or restart fresh from here?" Master the running sum first, and Kadane's will feel like a natural upgrade. 🚀
This is LeetCode #1480 — a classic warm-up that pros use to build intuition for prefix sums, Kadane's, and beyond. Let's get that running total going!
def running_sum(nums):
result = []
total = 0
for num in nums:
total += num
result.append(total)
return result
print(running_sum([1, 2, 3, 4]))
print(running_sum([1, 1, 1, 1, 1]))
print(running_sum([3, 1, 2, 10, 1]))