SlideShare ist ein Scribd-Unternehmen logo
1 von 4
Downloaden Sie, um offline zu lesen
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!

Weitere ähnliche Inhalte

Ähnlich wie 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
 

Ähnlich wie Maximum Subarray Sum in Python (20)

Arrays
ArraysArrays
Arrays
 
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
 

Kürzlich hochgeladen

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Kürzlich hochgeladen (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

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!