Mark As Completed Discussion

Brute Force Approach

The simplest solution to the problem is using the Brute Force approach:

  • Find all the possible contiguous subarrays.
  • Calculate their sum.
  • Find the maximum of all the sums.

Now going back to our input array to understand the Brute Force solution to the problem:

Brute Force Approach
In the above example, we can see that we'll have to calculate the sum of all the possible contiguous subarrays starting at index 0 to n-1. The above illustration is for index 0. The same step will be repeated for all the indices. Let's understand this solution to find the globalMaxSum:

  • This approach will require two loops.
  • An outer loop with index i that will iterate from 0 to n-1.
  • An inner loop with index j that will iterate from j set to i to n-1.
  • The inner loop will calculate subArraySum:
SNIPPET
1subArraySum = subArraySum + input[j]
  • Meanwhile, subArraySum will be compared with globalMaxSum.
  • If globalMaxSum will be less than subArraySum, then globalMaxSum will be set to subArraySum.
  • In the end, we'll be able to find out the largest sum of a contiguous subarray.
  • Note that the time complexity for this algorithm is O(n2)

Now heading to implementation in code to get a clearer understanding:

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment