Given an input array that may contain both positive and negative integers, find the sum of continuous subarray of numbers which has the largest sum.
Example:
Input: nums = [-2, -5, 6, -2, -3, 1, 5, -6]
Output: 7
Explanation: sum([6, -2, -3, 1, 5]) = 7
Note:
Your algorithm should run in O(n^2) time and use O(1) extra space.
Let's come up with a brute force approach. Brute force tries each and every candidate to our solution. For this problem, the candidates are all the subarrays of
nums.
How can we try out each subarray?
A subarray is defined by its left endpoint, let's name it index
i and its right point, let's name it index j.
We should go through each pair of indices (i, j) such that 0 <= i <= j < n.
How can we achieve this?
Using two nested for loops! The first loop will try out each possible
i between 0 and n - 1.
The second loop will be written inside the first one and will try out each possible j between i and n - 1.
for each i : 0 -> n - 1:
for each j : i -> n - 1:
We will use a variable maxSum to store the greatest sum found so far and for each pair (i, j), update maxSum with sum(nums[i...j]) if it's the case:
maxSum = nums[0]
for each i : 0 -> n - 1:
for each j : i -> n - 1:
maxSum = max(maxSum, sum(nums[i...j]))
return maxSum
All we have to do now is find a way of getting sum(nums[i...j]) in O(1) time. How can we do this?
One way is using Partial Sums. But that implies using an extra array which gives extra space of O(n). There is a better way. We can use a variable
sum to store the sum of the current subarray sum(nums[i...j]).
maxSum = nums[0]
for each i : 0 -> n - 1:
for each j : i -> n - 1:
maxSum = max(maxSum, sum)
return maxSum
How should we update this variable throught the algorithm to make sure that it always stores the correct sum?
Each time we increment
j in the second loop, we should add nums[j] to sum.
Also, each time we increment i in the first loop, we start with a new empty subarray so we should reset sum to 0:
maxSum = nums[0]
for each i : 0 -> n - 1:
sum = 0
for each j : i -> n - 1:
sum += nums[j]
maxSum = max(maxSum, sum)
return maxSum
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check