Maximum Sum Subarray

You are given an array (ARR) of length N, consisting of integers. You have to find the sum of the subarray (including empty subarray) having maximum sum among all subarrays.

A subarray is a contiguous segment of an array. In other words, a subarray can be formed by removing 0 or more integers from the beginning, and 0 or more integers from the end of an array.

Note :
The sum of an empty subarray is 0.
Input Format :
The first line of input contains an integer N, representing the length of the array.

The second line of input contains N single space-separated integers, denoting the elements of the array.
Output Format :
In the only output line, output the maximum subarray sum.
Note :
You are not required to print the output explicitly, it has already been taken care of. Just implement the function.
Constraints :
1 <= N <= 10^6
-10^6 <= A[i] <= 10^6

where N is the length of the array.
A[i] represents the numbers present in the array.

Time limit: 1sec
CodingNinjas
author
2y

The direct approach to solve this problem is to run two for loops and for every subarray check if it is the maximum sum possible.
Time complexity : O(N^2), Where N is the size of the array.
Space compl...read more

CodingNinjas
author
2y
Brute Force Approach

Let us check for all possible subarrays of the array. For this, we run two loops, where the outer loop points to the left boundary and the inner loop points to the outer boundary o...read more

CodingNinjas
author
2y
Boundary Fix Approach

According to the previous approach, let us fix the left boundary of the subarray in the outer loop. In the inner loop, we move our right boundary by one unit, every time.

Let’s sa...read more

CodingNinjas
author
2y
Divide And Conquer Approach
  1. Divide the array into 2 halves.
  2. Get the answer of left and right parts of the array by recursion.
  3. Get the answer of Maximum subarray sum such that the subarray crosses the mid...read more
CodingNinjas
author
2y
Sum Array Approach

Let us start from the left of the array. We maintain an array curSum[], which keeps track of the maximum sum of the subarray ending at the index we’re at.

While traversing the array,...read more

CodingNinjas
author
2y
Inplace Approach

Looking at the previous approach,we realize that to compute curSum[i], we only require the value of curSum[i-1]. Hence, instead of maintaining a whole array, we can simply keep track o...read more

Add answer anonymously...
BigStep Technologies Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter