- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to find the maximum subarray sum O(n^2) time (naive method)
We shall develop a C++ program to find the maximum subarray sum O(n^2) time (naive method).
Algorithm
Begin Take the array elements as input. Make a loop for the length of the sub-array from 1 to n, within this loop, Make another loop nested with the previous one, calculate the sum of first sub-array of that length. For remaining sub-array sum, add the next element to the sum and subtract the first element of that sub-array. Compare it with the global max and update if found out to be more. Print the max sub-array and their sum as a result. End.
Example Code
#include<iostream> using namespace std; int main() { int n, i, j, m=-1, s, ini_m, fi_m; cout<<"\nEnter the number of data element in the array: "; cin>>n; int a[n]; for(i = 0; i < n; i++) { cout<<"Enter element "<<i+1<<": "; cin>>a[i]; } for(i = 1; i < n+1; i++) { s = 0; for(j = 0; j < n; j++) { if(j < i) s += a[j]; else s = s+a[j]-a[j-i]; if(m< s) { ini_m = j-i+1; fi_m = j; m = s; } } } cout<<"\nThe maximum sub array is: "; for(i = ini_m; i <= fi_m; i++) cout<<a[i]<<" "; cout<<"\nThe maximum sub-array sum is: "<<m; }
Output
Enter the number of data element in the array: 10 Enter element 1: 1 Enter element 2: -2 Enter element 3: 3 Enter element 4: -4 Enter element 5: 5 Enter element 6: -6 Enter element 7: 7 Enter element 8: 8 Enter element 9: -9 Enter element 10: 10 The maximum sub array is: 7 8 -9 10 The maximum sub-array sum is: 16
- Related Articles
- Maximum subarray sum in O(n) using prefix sum in C++
- C++ Program to Find the maximum subarray sum using Binary Search approach
- Program to find maximum ascending subarray sum using Python
- Find Maximum Sum Strictly Increasing Subarray in C++
- Program to find maximum absolute sum of any subarray in Python
- Maximum Subarray Sum Excluding Certain Elements in C++ program
- Program to find the maximum sum of the subarray modulo by m in Python
- Maximum Sum Circular Subarray in C++
- Maximum circular subarray sum in C++
- Maximum sum bitonic subarray in C++
- Find the maximum repeating number in O(n) time and O(1) extra space in Python
- C/C++ Program to Find the sum of Series with the n-th term as n^2 – (n-1)^2
- Program to find out the sum of the maximum subarray after a operation in Python
- Maximum subarray sum modulo m in C++
- Find four factors of N with maximum product and sum equal to N - Set-2 in Python Program

Advertisements