SlideShare uma empresa Scribd logo
1 de 4
Baixar para ler offline
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!

Mais conteúdo relacionado

Semelhante a Maximum Subarray Sum in Python

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
ShahinAhmed49
 
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
aroraopticals15
 
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
ArjunSingh81957
 

Semelhante a 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
 

Último

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
heathfieldcps1
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Último (20)

Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
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
 
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
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
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
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
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
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
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
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 

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!