Answer to Question #191224 in C for CHANDAN MIshra

Question #191224

Maximum Subarray Sum (Divide and Conquer)

Description

You are given an array containing 'n' elements. The array can contain both positive and negative integers. Determine the sum of the contiguous subarray with the maximum sum.

 

Consider the array {8, -9, 3, 6, 8, -5, 7, -6, 1, -3}.

The maximum subarray will be 3, 6, 8, -5, 7.

The maximum subarray sum will be 3+6+8+(-5)+7 = 19

 

Input Format:

The input contains the number of elements in the array, followed by the elements in the array.

 

Output Format:

The output contains the maximum subarray sum.

 

Sample Test Cases:

Input:

10 8 -9 3 6 8 -5 7 -6 1 -3


Output:

19 

 

Input:

5 8 9 4 5 7

 

Output:

33


1
Expert's answer
2021-05-10T02:11:42-0400
#include<stdio.h>
#include<string.h>
#include<ctype.h>


int maxSubArraySum(int elements[],int n);


int main(){
	int elements[1000];
	int n=10;
	int i=0;
	scanf("%d",&n);
	for(i=0;i<n;i++){
		scanf("%d",&elements[i]);
	}
	int maxSubSum= maxSubArraySum(elements,n);
	printf("%d\n\n",maxSubSum);
	getchar();
	getchar();
	return 0;
}


//use the Kadane Algorithm
int maxSubArraySum(int elements[],int n) {


	int maxElement = 0;
	int maxEndingElement = 0;
	for (int i = 0; i < n; i++) {
		maxEndingElement += elements[i];
		if (maxEndingElement < 0){
			maxEndingElement = 0;
		}else if (maxElement < maxEndingElement){
			maxElement = maxEndingElement;
		}
	}
	return maxElement;
}



Examples:



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS