Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Largest Sum Contiguous Subarray
An array of integers is given. We have to find the sum of all elements which are contiguous, whose sum is largest, that will be sent as output.
Using dynamic programming we will store the maximum sum up to current term. It will help to find the sum for contiguous elements in the array.
Input and Output
Input:
An array of integers. {-2, -3, 4, -1, -2, 1, 5, -3}
Output:
Maximum Sum of the Subarray is: 7
Algorithm
maxSum(array, n)
Input − The main array, the size of the array.
Output − maximum sum.
Begin tempMax := array[0] currentMax = tempMax for i := 1 to n-1, do currentMax = maximum of (array[i] and currentMax+array[i]) tempMax = maximum of (currentMax and tempMax) done return tempMax End
Example
#includeusing namespace std; int maxSum( int arr[], int n) { int tempMax = arr[0]; int currentMax = tempMax; for (int i = 1; i Output
Maximum Sum of the Sub-array is: 7
Advertisements
