💡
Exercise 15

Running Sum — Your Array's Bank Balance 💰 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

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]:

  • Index 0: just 1 → result is 1
  • Index 1: 1 + 2 = 3 → result is 3
  • Index 2: 1 + 2 + 3 = 6 → result is 6
  • Index 3: 1 + 2 + 3 + 4 = 10 → result is 10

So 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:

total = 0 for num in nums: total += num # add current element to running total # total now holds the sum from index 0 to here!

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!

📋 Instructions
Write a function `running_sum(nums)` that takes a list of integers and returns a **new list** where each element at index `i` is the sum of all elements from index `0` to `i` (inclusive). **Example:** - Input: `[1, 2, 3, 4]` → Output: `[1, 3, 6, 10]` - Input: `[1, 1, 1, 1, 1]` → Output: `[1, 2, 3, 4, 5]` Print the results of all three test cases to match the expected output.
Keep a running total variable, starting at 0. Loop through each element — add it to the total, then append the total to your result list. That's it! One pass, O(n) time. 🎯
⚠️ Try solving it yourself first — you'll learn more!
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]))
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.