Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Maximum Circular Subarray Sum
Next article icon
Try it on GfG Practice
redirect icon

Given an integer arrayarr[], find thesubarray (containing at least one element) which has themaximum possible sum, and return that sum.
Note:Asubarray is a continuous part of an array.

Examples:

Input:arr[] = [2, 3, -8, 7, -1, 2, 3]
Output: 11
Explanation:The subarray [7, -1, 2, 3] has the largest sum 11.

Input:arr[] = [-2, -4]
Output:-2
Explanation:The subarray [-2] has the largest sum -2.

Input:arr[] = [5, 4, 1, 7, 8]
Output: 25
Explanation: The subarray [5, 4, 1, 7, 8] has the largest sum 25.

[Naive Approach] By iterating over all subarrays - O(n^2) Time and O(1) Space

The idea is to run two nested loops to iterate over all possible subarrays and find the maximum sum. The outer loop will mark the starting point of a subarray and inner loop will mark the ending point of the subarray.

C++
#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;intmaxSubarraySum(vector<int>&arr){intres=arr[0];// Outer loop for starting point of subarrayfor(inti=0;i<arr.size();i++){intcurrSum=0;// Inner loop for ending point of subarrayfor(intj=i;j<arr.size();j++){currSum=currSum+arr[j];// Update res if currSum is greater than resres=max(res,currSum);}}returnres;}intmain(){vector<int>arr={2,3,-8,7,-1,2,3};cout<<maxSubarraySum(arr);return0;}
C
#include<stdio.h>intmaxSubarraySum(intarr[],intsize){intmaxSum=arr[0];// Outer loop for starting point of subarrayfor(inti=0;i<size;i++){intcurrSum=0;// Inner loop for ending point of subarrayfor(intj=i;j<size;j++){currSum=currSum+arr[j];// Update maxSum if currSum is greater than maxSumif(currSum>maxSum){maxSum=currSum;}}}returnmaxSum;}intmain(){intarr[]={2,3,-8,7,-1,2,3};intsize=sizeof(arr)/sizeof(arr[0]);printf("%d",maxSubarraySum(arr,size));return0;}
Java
importjava.util.Arrays;classGfG{staticintmaxSubarraySum(int[]arr){intres=arr[0];// Outer loop for starting point of subarrayfor(inti=0;i<arr.length;i++){intcurrSum=0;// Inner loop for ending point of subarrayfor(intj=i;j<arr.length;j++){currSum=currSum+arr[j];// Update res if currSum is greater than resres=Math.max(res,currSum);}}returnres;}publicstaticvoidmain(String[]args){int[]arr={2,3,-8,7,-1,2,3};System.out.println(maxSubarraySum(arr));}}
Python
defmaxSubarraySum(arr):res=arr[0]# Outer loop for starting point of subarrayforiinrange(len(arr)):currSum=0# Inner loop for ending point of subarrayforjinrange(i,len(arr)):currSum=currSum+arr[j]# Update res if currSum is greater than resres=max(res,currSum)returnresif__name__=="__main__":arr=[2,3,-8,7,-1,2,3]print(maxSubarraySum(arr))
C#
usingSystem;classGfG{staticintMaxSubarraySum(int[]arr){intres=arr[0];// Outer loop for starting point of subarrayfor(inti=0;i<arr.Length;i++){intcurrSum=0;// Inner loop for ending point of subarrayfor(intj=i;j<arr.Length;j++){currSum=currSum+arr[j];// Update res if currSum is greater than resres=Math.Max(res,currSum);}}returnres;}staticvoidMain(){int[]arr={2,3,-8,7,-1,2,3};Console.WriteLine(MaxSubarraySum(arr));}}
JavaScript
functionmaxSubarraySum(arr){letres=arr[0];// Outer loop for starting point of subarrayfor(leti=0;i<arr.length;i++){letcurrSum=0;// Inner loop for ending point of subarrayfor(letj=i;j<arr.length;j++){currSum=currSum+arr[j];// Update res if currSum is greater than resres=Math.max(res,currSum);}}returnres;}constarr=[2,3,-8,7,-1,2,3];console.log(maxSubarraySum(arr));

Output
11

[Expected Approach] Using Kadane's Algorithm - O(n) Time and O(1) Space

The idea ofKadane's algorithmis to traverse over the array from left to right and for each element, find the maximum sum amongall subarrays ending at that element. The result will be the maximum of all these values.

To calculate the maximum sum of subarray ending at current element, saymaxEnding, we can use the maximum sum ending at the previous element.

So for any element, we have two choices:

Choice 1:Extend the maximum sum subarray ending at the previous element by adding the current element to it. If the maximum subarray sum ending at the previous index ispositive, then it is always better to extend the subarray.

Choice 2:Start a new subarray starting from the current element. If the maximum subarray sum ending at the previous index isnegative, it is always better to start a new subarray from the current element.

This means thatmaxEnding at index i = max(maxEnding at index (i - 1) + arr[i], arr[i]) and themaximumvalue of maxEnding at any index will be our answer.

Illustration:

C++
#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;intmaxSubarraySum(vector<int>&arr){// Stores the result (maximum sum found so far)intres=arr[0];// Maximum sum of subarray ending at current positionintmaxEnding=arr[0];for(inti=1;i<arr.size();i++){// Either extend the previous subarray or start// new from current elementmaxEnding=max(arr[i],maxEnding+arr[i]);// Update result if the new subarray sum is largerres=max(res,maxEnding);}returnres;}intmain(){vector<int>arr={2,3,-8,7,-1,2,3};cout<<maxSubarraySum(arr);return0;}
C
#include<stdio.h>#include<limits.h>intmaxSubarraySum(intarr[],intsize){// Stores the result (maximum sum found so far)intres=arr[0];// Maximum sum of subarray ending at current positionintmaxEnding=arr[0];for(inti=1;i<size;i++){// Either extend the previous subarray or start// new from current elementmaxEnding=(maxEnding+arr[i]>arr[i])?maxEnding+arr[i]:arr[i];// Update result if the new subarray sum is largerres=(res>maxEnding)?res:maxEnding;}returnres;}intmain(){intarr[]={2,3,-8,7,-1,2,3};intsize=sizeof(arr)/sizeof(arr[0]);printf("%lld\n",maxSubarraySum(arr,size));return0;}
Java
importjava.util.Arrays;classGfG{staticintmaxSubarraySum(int[]arr){// Stores the result (maximum sum found so far)intres=arr[0];// Maximum sum of subarray ending at current positionintmaxEnding=arr[0];for(inti=1;i<arr.length;i++){// Either extend the previous subarray or start// new from current elementmaxEnding=Math.max(maxEnding+arr[i],arr[i]);// Update result if the new subarray sum is largerres=Math.max(res,maxEnding);}returnres;}publicstaticvoidmain(String[]args){int[]arr={2,3,-8,7,-1,2,3};System.out.println(maxSubarraySum(arr));}}
Python
# Function to find the maximum subarray sumdefmaxSubarraySum(arr):# Stores the result (maximum sum found so far)res=arr[0]# Maximum sum of subarray ending at current positionmaxEnding=arr[0]foriinrange(1,len(arr)):# Either extend the previous subarray or start# new from current elementmaxEnding=max(maxEnding+arr[i],arr[i])# Update result if the new subarray sum is largerres=max(res,maxEnding)returnresif__name__=="__main__":arr=[2,3,-8,7,-1,2,3]print(maxSubarraySum(arr))
C#
usingSystem;classGfG{staticintmaxSubarraySum(int[]arr){// Stores the result (maximum sum found so far)intres=arr[0];// Maximum sum of subarray ending at current positionintmaxEnding=arr[0];for(inti=1;i<arr.Length;i++){// Either extend the previous subarray or start// new from current elementmaxEnding=Math.Max(maxEnding+arr[i],arr[i]);// Update result if the new subarray sum is largerres=Math.Max(res,maxEnding);}returnres;}staticvoidMain(){int[]arr={2,3,-8,7,-1,2,3};Console.WriteLine(maxSubarraySum(arr));}}
JavaScript
functionmaxSubarraySum(arr){// Stores the result (maximum sum found so far)letres=arr[0];// Maximum sum of subarray ending at current positionletmaxEnding=arr[0];for(leti=1;i<arr.length;i++){// Either extend the previous subarray or start// new from current elementmaxEnding=Math.max(maxEnding+arr[i],arr[i]);// Update result if the new subarray sum is largerres=Math.max(res,maxEnding);}returnres;}// Driver Codeconstarr=[2,3,-8,7,-1,2,3];console.log(maxSubarraySum(arr));

Output
11

Related Articles:


Maximum Subarray Sum
Visit Courseexplore course icon
Video Thumbnail

Maximum Subarray Sum

Video Thumbnail

Maximum Sum Subarray

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp