Maximum Subarray Sum

You are given an array/list ARR consisting of N integers. Your task is to find the maximum possible sum of a non-empty subarray(contagious) of this array.

Note: An array C is a subarray of array D if it can be obtained by deletion of several elements(possibly zero) from the beginning and the end of array D.

For e.g.- All the non-empty subarrays of array [1,2,3] are [1], [2], [3], [1,2], [2,3], [1,2,3].

Input Format
The first line of input contains a single integer ‘N’ denoting the number of elements in the array/list.

The second line of input contains ‘N’ single space-separated integers, denoting the elements of the array.
Output Format :
Print the maximum possible sum of any subarray of the array/list. 

Note: You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= N <= 5*10^5
-10^9 <= ARR[i] <=10^9

Time Limit: 1sec
CodingNinjas
author
2y

Approach (Using Kadane's Algo) :

1) Declare a variable ‘maxSum’ and initialize it with ‘minimum integer’.

2) Declare a variable ‘localSum’ and initialize it with ‘0’.

3) Declare 3 counter variables as ‘s...read more

CodingNinjas
author
2y
Brute Force

We will iterate through all possible boundaries of the subarrays in the given array with the help of two nested loops.

Then, we will iterate through each subarray with the help of another ...read more

CodingNinjas
author
2y
Brute Force Optimized

We will iterate through all possible subarrays of the array with the help of two nested loops. We will maintain the maximum subarray sum/answer through our iterations and finally ...read more

CodingNinjas
author
2y
Kadane's Algorithm

The main observation here is that the optimal subarray will have no prefix with a negative sum. This is because we can remove the prefix with a negative sum from our optimal subarray...read more

Add answer anonymously...
Capita Software Developer 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