# Leetcode 53: Maximum SubArray Sum

One of the Leetcode problems that I worked on this week is called Maximum Subarray Sum. If you would like to try it yourself, you can find it here. Although this is a relatively simple problem, I learned something new about JavaScript in the process of solving it, which is always great. I’m going to do a brief walkthrough of the problem and my solution, and I hope that it helps anyone who may be stuck.

## The Problem

Write a function that takes an array as an argument. This function should find the subarray with the greatest sum, and return that sum. For example, if the array was [ 1,- 5, 4, 5 ], the function would return 9, since [4,5] is the subarray with the greatest sum. Also, it is important to note that if all of the numbers in the array are positive, the entire array will be the subarray with the greatest sum.

## My Approach

I had a fairly solid idea of how I wanted to approach this problem going into it. I decided to create two variables and set them to 0. One of these variables would serve to keep track of the current total of array values, and the other would store the highest total by comparing itself to the current total. Then, I would loop through the array and add the value at each index to the current total. If the current total was greater than the highest total, the highest total would become the current total. This seemed relatively straightforward, but I hit an unexpected bug. Below, you can see my original solution before I refactored it.