SlideShare une entreprise Scribd logo
1  sur  4
Télécharger pour lire hors ligne
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!

Contenu connexe

Similaire à 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
 

Similaire à 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
 

Dernier

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
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
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
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
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 

Dernier (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
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
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
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
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

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!