DEV Community

Posted on

Day 43/366

🚀 Today's Learning:


  • calculate the largest subarray sum
  • print the subarray with the largest sum

🌟 Dev

  • JWT Authorization

🔍 Some Key Highlights:


To calculate the largest subarray sum, we use Kadane's Algorithm. We initialize two variables, maxCurrent and maxGlobal, with the first element of the array. We then iterate through the array starting from the second element. For each element, we update maxCurrent to be the maximum of the current element and the sum of maxCurrent and the current element. This step ensures that we are either starting a new subarray at the current element or continuing the existing subarray. We then update maxGlobal to be the maximum of maxGlobal and maxCurrent. By the end of the iteration, maxGlobal holds the largest sum of any subarray within the given array.

To print the subarray with the largest sum, we use a similar approach with Kadane's Algorithm, but with additional tracking of the start and end indices of the subarray. We initialize variables for the current and global maximums, and for the start and end indices. As we iterate through the array, we update maxCurrent in the same way, but also track when we start a new subarray by recording the current index as the start. If maxCurrent exceeds maxGlobal, we update maxGlobal and set the start and end indices to the current tracked start and current index, respectively. After completing the iteration, we print the subarray that starts at the recorded start index and ends at the recorded end index, which represents the subarray with the largest sum.

#100daysofcode #1percentplusplus #coding #dsa

Top comments (0)