1+ """
2+ =========================================================
3+ 53. Maximum Subarray - Brute Force Approach
4+ =========================================================
5+
6+ Problem:
7+ ---------
8+ Given an integer array nums, find the contiguous subarray
9+ (containing at least one number) which has the largest sum,
10+ and return its sum.
11+
12+ Example:
13+ ---------
14+ Input:
15+ nums = [-2,1,-3,4,-1,2,1,-5,4]
16+
17+ Output:
18+ 6
19+
20+ Explanation:
21+ The subarray [4, -1, 2, 1] has the largest sum = 6.
22+
23+ ---------------------------------------------------------
24+ Brute Force Intuition:
25+ ---------------------------------------------------------
26+ Generate all possible contiguous subarrays and calculate
27+ their sums.
28+
29+ Keep track of the maximum sum encountered so far.
30+
31+ Instead of recalculating each subarray sum from scratch,
32+ we maintain a running sum:
33+
34+ For every starting index i:
35+ Initialize current_sum = 0
36+
37+ For every ending index j:
38+ Add nums[j] to current_sum
39+ Update max_sum
40+
41+ ---------------------------------------------------------
42+ Approach:
43+ ---------------------------------------------------------
44+ 1. Iterate through every possible starting index.
45+ 2. For each starting index:
46+ - Initialize current_sum = 0
47+ 3. Extend the subarray one element at a time.
48+ 4. Update the maximum subarray sum found so far.
49+ 5. Return max_sum.
50+
51+ ---------------------------------------------------------
52+ Dry Run:
53+ ---------------------------------------------------------
54+ nums = [-2,1,-3,4,-1,2,1,-5,4]
55+
56+ i = 0
57+ [-2] -> -2
58+ [-2,1] -> -1
59+ [-2,1,-3] -> -4
60+ ...
61+
62+ i = 3
63+ [4] -> 4
64+ [4,-1] -> 3
65+ [4,-1,2] -> 5
66+ [4,-1,2,1] -> 6 <-- Maximum
67+
68+ Answer = 6
69+
70+ ---------------------------------------------------------
71+ Time Complexity:
72+ ---------------------------------------------------------
73+ O(n²)
74+
75+ Outer loop runs n times.
76+ Inner loop runs up to n times.
77+
78+ ---------------------------------------------------------
79+ Space Complexity:
80+ ---------------------------------------------------------
81+ O(1)
82+
83+ Only a few extra variables are used.
84+
85+ =========================================================
86+ """
87+
88+ from typing import List
89+
90+
91+ class Solution :
92+ def maxSubArray (self , nums : List [int ]) -> int :
93+ max_sum = float ("-inf" )
94+
95+ for i in range (len (nums )):
96+ current_sum = 0
97+
98+ for j in range (i , len (nums )):
99+ current_sum += nums [j ]
100+ max_sum = max (max_sum , current_sum )
101+
102+ return max_sum
0 commit comments