
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
C/C++ Program for Largest Sum Contiguous Subarray?
An array of integers is given. We have to find 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 sum for contiguous elements in the array.
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
#include<iostream> using namespace std; int maxSum( int arr[], int n) { int tempMax = arr[0]; int currentMax = tempMax; for (int i = 1; i < n; i++ ) { //find the max value currentMax = max(arr[i], currentMax+arr[i]); tempMax = max(tempMax, currentMax); } return tempMax; } int main() { int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = 8; cout << "Maximum Sum of the Sub-array is: "<< maxSum( arr, n ); }
Output
Maximum Sum of the Sub-array is: 7
- Related Articles
- Largest Sum Contiguous Subarray
- Maximum contiguous sum of subarray in JavaScript
- Largest subarray having sum greater than k in C++
- C++ program to find maximum of each k sized contiguous subarray
- Largest sum subarray with at-least k numbers in C++
- Program to find maximum product of contiguous subarray in Python
- Write a program in C++ to find the length of the largest subarray with zero sum
- Maximum Subarray Sum Excluding Certain Elements in C++ program
- Contiguous subarray with 0 and 1 in JavaScript
- Largest product of contiguous digits in Python
- Continuous Subarray Sum in C++
- Find Sum of all unique subarray sum for a given array in C++
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find sum of the sum of all contiguous sublists in Python
- Subarray Sum Equals K in C++

Advertisements