700542. Play with an array

Basic

Here is the detailed Markdown blog post for the GeeksforGeeks problem "Play with an array":

Play with an Array

Summary

Given an array of integers, you need to find the maximum sum of a contiguous subarray within it. This problem involves arrays and data structures.

Detailed Explanation

The problem can be solved by using the concept of Kadane's algorithm. The idea is to maintain two variables: the current maximum sum (CMS) and the maximum sum so far (MSF). Initialize MSF with the first element of the array, and CMS with the same value. Iterate through the array starting from the second element.

Step-by-step breakdown:

  1. For each element arr[i], calculate the current maximum sum (CMS) as the maximum of arr[i-1] + arr[i] and arr[i]. This is because a subarray ending at i can either be extended by adding arr[i] to the previous subarray or start anew with arr[i].
  2. Update MSF if CMS becomes greater than it.
  3. Repeat steps 1-2 until you have processed all elements in the array.

Time complexity: O(n), where n is the number of elements in the array, since we only need to iterate through the array once.

Space complexity: O(1), as we are only using a constant amount of space to store CMS and MSF.

Optimized Solutions

Here are some optimized solutions for this problem:

Java

View on GeeksforGeeks
public int maxSubArraySum(int[] arr) {
    int msf = arr[0];
    int cms = arr[0];
    for (int i = 1; i < arr.length; i++) {
        cms = Math.max(arr[i], cms + arr[i]);
        msf = Math.max(msf, cms);
    }
    return msf;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.