SlideShare una empresa de Scribd logo
1 de 4
Descargar para leer sin conexión
Python Array Challenges Python Coding Challenges
Maximum Subarray Sum in Python
written by Kal Bartal February 4, 2023
Click to watch video tutorial on Maximum Subarray Sum in Python Video Tutorial on YouTube
Problem Statement:
Given an array of integers, find the contiguous subarray (containing at least one number) which
has the largest sum and return its sum.
Example:
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
Explanation: The contiguous subarray [4, -1, 2, 1] has the largest sum = 6.
Understanding the problem
This problem is all about finding the maximum sum of a continuous sequence of numbers within
an array. All we need to do is look at each contiguous subarray and find the one with the largest
sum. A contiguous subarray is just a subset of an array and must include at least one number.
We just need to make sure that we return the maximum sum.
For example, given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum sum is 6
because the subarray [4, -1, 2, 1] has the largest sum.
Solving this problem
Well, the first thing you should know is the concept of a subarray. A subarray is just a subset of
an array and it must include at least one number. Then, you should also understand how to find
the sum of a subarray. This can just be done by adding up all the numbers in the subarray. Lastly,
you should know how to compare different subarrays and find the one with the largest sum.
Once you understand the basics, solving this problem should be easier. You just have to make
sure that you go through each subarray and compare the sums. Then, you can return the
maximum sum.
Subarrays in Arrays
– Sum subarrays by adding their numbers.
– Maximum Subarray Sum finds max sum of subarrays.
– Subarrays must have consecutive elements.
A subarray is just a subset of an array. It must include at least one number and the elements
must be consecutive within the same array. The subarrays can be of any size, as long as the
elements are all next to each other. We will be using subarrays in the Maximum Subarray Sum
problem to find the subarray with the largest sum.
Example: If we had the array [2, 4, 6, 8], then the subarrays could be [2] [4], [6], [8],
[2, 4], [4, 6], [6, 8], [2,4,6], [4, 6, 8], and so on.
Calculating Subarray Sums
– Add up the numbers in a subarray to calculate its sum.
– Maximum Subarray Sum problem finds max sum of all subarrays.
– Sums need to be compared individually.
Finding the sum of a subarray is pretty straightforward. All you need to do is add up the numbers
in the subarray. We will use this principle to find the sum of each subarray and compare it to the
other subarrays to find the maximum sum.
Example: If we had the subarray [3, 4, 7], the sum would be 3 + 4 + 7 = 14.
Calculating the Subarray with the Largest Sum
– Calculate the sum of each subarray
– Compare the sums to all the other subarrays
– Return the subarray with the largest sum
Comparing different subarrays to find the one with the largest sum is pretty simple. All you need
to do is calculate the sum of each subarray and compare it to all the other subarrays. The
subarray with the largest sum will be the one you want to return.
Example: Given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum sum is 6
because the subarray [4, -1, 2, 1] has the largest sum.
Finding the Maximum Sum of a Subarray
We can use a dynamic programming approach to solve challenge. We can start by creating a list
to store the maximum sum of all subarrays from the beginning of the array to the current
position. We also need a variable to keep track of the maximum sum of all subarrays seen so
far.
We then loop through the array, and for each element, we calculate the maximum sum of the
subarray starting at the beginning, and add the current element to it. We then compare this
maximum sum to the maximum sum of all subarrays seen so far and update the maximum sum
if necessary. Once we have gone through the entire array, we will have the maximum sum of all
subarrays, which we can then return.
Here is a solution in Python that uses dynamic programming to solve the maximum subarray
sum problem:
def maxSubarraySum(arr):
# create a list to store the maximum sum of all subarrays from the beg
inning of the array to the current position
subarrays_sum = [0]
# variable to keep track of the maximum sum of all subarrays seen so f
ar
max_sum = 0
# loop through the array and calculate the maximum sum of the subarray
starting at the beginning, and add the
# current element to it
for num in arr:
subarrays_sum.append(max(subarrays_sum[-1] + num, num))
max_sum = max(max_sum, subarrays_sum[-1])
# return the maximum sum of all subarrays
return max_sum
# For example, given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximu
m sum is 6 because the subarray [4, -1, 2,
# 1] has the largest sum.
print(maxSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6
This code uses dynamic programming to solve the Maximum Subarray Sum problem. We start
by creating a list to store the maximum sum of all subarrays from the beginning of the array to
the current index. Then, we have a variable to keep track of the maximum sum of all subarrays
seen so far.
We then loop through the array and for each element, we calculate the maximum sum of the
subarray starting at the beginning and add the current element to it. We then compare this
maximum sum to the maximum sum of all subarrays seen so far and update the maximum sum
if necessary.
Once we have gone through the entire array, we will have the maximum sum of all subarrays,
which we can then return.
Time Complexity of Algorithm
– O(n), where n is the length of the array
– Loop array once, calculate max sum with constant time
– Efficient and able to handle large inputs
The time complexity of this code is O(n), where n is the length of the array. This is because we
only need to loop through the array once and for each element, the maximum sum of the
subarray is calculated with a constant time operation. This makes the time complexity of the
algorithm totally linear, making it really efficient and able to handle large input arrays without any
problems.
Space Complexity of Code
– Code runs on O(n), same as linear time
– List stores max sum of subarrays from the beginning of the array
– List size same as array length, consistent space needs
In terms of space complexity! It runs on O(n), the same as linear time. We’re using a list to store
the maximum sum of all subarrays from the beginning of the array, and the size of the list is the
same as the array’s length. This means the amount of space needed remains consistent even for
large input arrays.
Final Thoughts
– Efficient solution with time and space complexity of O(n)
– Think through a coding challenge
– Talk through the problem to ensure understanding
This is a great example of how powerful dynamic programming can be! It allows us to find the
most efficient solution for a problem, as well as giving us the chance to think about it in-depth.
Plus, a solid understanding of the problem is key, so it’s always important to ensure you
understand it before starting to code. Awesome work!

Más contenido relacionado

Similar a Maximum Subarray Sum in Python

Data structures arrays
Data structures   arraysData structures   arrays
Data structures arraysmaamir farooq
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programmingTaseerRao
 
Essential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdfEssential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdfSmrati Kumar Katiyar
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxShahinAhmed49
 
NUMPY [Autosaved] .pptx
NUMPY [Autosaved]                    .pptxNUMPY [Autosaved]                    .pptx
NUMPY [Autosaved] .pptxcoolmanbalu123
 
enhancement of sorting algorithm
enhancement of sorting algorithmenhancement of sorting algorithm
enhancement of sorting algorithmRana assad ali
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfArjunSingh81957
 
Java Arrays
Java ArraysJava Arrays
Java ArraysOXUS 20
 
Master the arrays and algorithms using Algotutor
Master the arrays and algorithms using AlgotutorMaster the arrays and algorithms using Algotutor
Master the arrays and algorithms using AlgotutorVivekanandaGN1
 
CAP776Numpy.ppt
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.pptkdr52121
 

Similar a Maximum Subarray Sum in Python (20)

Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
RNN.pdf
RNN.pdfRNN.pdf
RNN.pdf
 
Array and functions
Array and functionsArray and functions
Array and functions
 
Essential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdfEssential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdf
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
 
NUMPY [Autosaved] .pptx
NUMPY [Autosaved]                    .pptxNUMPY [Autosaved]                    .pptx
NUMPY [Autosaved] .pptx
 
14078956.ppt
14078956.ppt14078956.ppt
14078956.ppt
 
enhancement of sorting algorithm
enhancement of sorting algorithmenhancement of sorting algorithm
enhancement of sorting algorithm
 
Array-part1
Array-part1Array-part1
Array-part1
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Master the arrays and algorithms using Algotutor
Master the arrays and algorithms using AlgotutorMaster the arrays and algorithms using Algotutor
Master the arrays and algorithms using Algotutor
 
Array andfunction
Array andfunctionArray andfunction
Array andfunction
 
CAP776Numpy (2).ppt
CAP776Numpy (2).pptCAP776Numpy (2).ppt
CAP776Numpy (2).ppt
 
CAP776Numpy.ppt
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.ppt
 

Último

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 

Último (20)

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 

Maximum Subarray Sum in Python

  • 1. Python Array Challenges Python Coding Challenges Maximum Subarray Sum in Python written by Kal Bartal February 4, 2023 Click to watch video tutorial on Maximum Subarray Sum in Python Video Tutorial on YouTube Problem Statement: Given an array of integers, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4] Output: 6 Explanation: The contiguous subarray [4, -1, 2, 1] has the largest sum = 6. Understanding the problem This problem is all about finding the maximum sum of a continuous sequence of numbers within an array. All we need to do is look at each contiguous subarray and find the one with the largest sum. A contiguous subarray is just a subset of an array and must include at least one number. We just need to make sure that we return the maximum sum. For example, given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum sum is 6 because the subarray [4, -1, 2, 1] has the largest sum.
  • 2. Solving this problem Well, the first thing you should know is the concept of a subarray. A subarray is just a subset of an array and it must include at least one number. Then, you should also understand how to find the sum of a subarray. This can just be done by adding up all the numbers in the subarray. Lastly, you should know how to compare different subarrays and find the one with the largest sum. Once you understand the basics, solving this problem should be easier. You just have to make sure that you go through each subarray and compare the sums. Then, you can return the maximum sum. Subarrays in Arrays – Sum subarrays by adding their numbers. – Maximum Subarray Sum finds max sum of subarrays. – Subarrays must have consecutive elements. A subarray is just a subset of an array. It must include at least one number and the elements must be consecutive within the same array. The subarrays can be of any size, as long as the elements are all next to each other. We will be using subarrays in the Maximum Subarray Sum problem to find the subarray with the largest sum. Example: If we had the array [2, 4, 6, 8], then the subarrays could be [2] [4], [6], [8], [2, 4], [4, 6], [6, 8], [2,4,6], [4, 6, 8], and so on. Calculating Subarray Sums – Add up the numbers in a subarray to calculate its sum. – Maximum Subarray Sum problem finds max sum of all subarrays. – Sums need to be compared individually. Finding the sum of a subarray is pretty straightforward. All you need to do is add up the numbers in the subarray. We will use this principle to find the sum of each subarray and compare it to the other subarrays to find the maximum sum. Example: If we had the subarray [3, 4, 7], the sum would be 3 + 4 + 7 = 14. Calculating the Subarray with the Largest Sum – Calculate the sum of each subarray – Compare the sums to all the other subarrays – Return the subarray with the largest sum
  • 3. Comparing different subarrays to find the one with the largest sum is pretty simple. All you need to do is calculate the sum of each subarray and compare it to all the other subarrays. The subarray with the largest sum will be the one you want to return. Example: Given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum sum is 6 because the subarray [4, -1, 2, 1] has the largest sum. Finding the Maximum Sum of a Subarray We can use a dynamic programming approach to solve challenge. We can start by creating a list to store the maximum sum of all subarrays from the beginning of the array to the current position. We also need a variable to keep track of the maximum sum of all subarrays seen so far. We then loop through the array, and for each element, we calculate the maximum sum of the subarray starting at the beginning, and add the current element to it. We then compare this maximum sum to the maximum sum of all subarrays seen so far and update the maximum sum if necessary. Once we have gone through the entire array, we will have the maximum sum of all subarrays, which we can then return. Here is a solution in Python that uses dynamic programming to solve the maximum subarray sum problem: def maxSubarraySum(arr): # create a list to store the maximum sum of all subarrays from the beg inning of the array to the current position subarrays_sum = [0] # variable to keep track of the maximum sum of all subarrays seen so f ar max_sum = 0 # loop through the array and calculate the maximum sum of the subarray starting at the beginning, and add the # current element to it for num in arr: subarrays_sum.append(max(subarrays_sum[-1] + num, num)) max_sum = max(max_sum, subarrays_sum[-1]) # return the maximum sum of all subarrays return max_sum # For example, given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximu m sum is 6 because the subarray [4, -1, 2, # 1] has the largest sum. print(maxSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6 This code uses dynamic programming to solve the Maximum Subarray Sum problem. We start by creating a list to store the maximum sum of all subarrays from the beginning of the array to the current index. Then, we have a variable to keep track of the maximum sum of all subarrays seen so far. We then loop through the array and for each element, we calculate the maximum sum of the subarray starting at the beginning and add the current element to it. We then compare this
  • 4. maximum sum to the maximum sum of all subarrays seen so far and update the maximum sum if necessary. Once we have gone through the entire array, we will have the maximum sum of all subarrays, which we can then return. Time Complexity of Algorithm – O(n), where n is the length of the array – Loop array once, calculate max sum with constant time – Efficient and able to handle large inputs The time complexity of this code is O(n), where n is the length of the array. This is because we only need to loop through the array once and for each element, the maximum sum of the subarray is calculated with a constant time operation. This makes the time complexity of the algorithm totally linear, making it really efficient and able to handle large input arrays without any problems. Space Complexity of Code – Code runs on O(n), same as linear time – List stores max sum of subarrays from the beginning of the array – List size same as array length, consistent space needs In terms of space complexity! It runs on O(n), the same as linear time. We’re using a list to store the maximum sum of all subarrays from the beginning of the array, and the size of the list is the same as the array’s length. This means the amount of space needed remains consistent even for large input arrays. Final Thoughts – Efficient solution with time and space complexity of O(n) – Think through a coding challenge – Talk through the problem to ensure understanding This is a great example of how powerful dynamic programming can be! It allows us to find the most efficient solution for a problem, as well as giving us the chance to think about it in-depth. Plus, a solid understanding of the problem is key, so it’s always important to ensure you understand it before starting to code. Awesome work!