
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum Sum of Strictly Increasing Subarray in C++
Suppose we have an array of n integers. Find the max sum of strictly increasing subarrays. So if the array is like [1, 2, 3, 2, 5, 1, 7], the sum is 8. In this array there are three strictly increasing sub-arrays these are {1, 2, 3}, {2, 5} and {1, 7}. The max sum sub-array is {1, 7}
To solve this problem, we have to keep track of max sum and the current sum. For each element arr[i] if this is larger than arr[i – 1], then we add this to the current sum, otherwise arr[i] is the starting point of another subarray. So we shall update the current sum as array. Before updating current sum, we will update max sum if required.
Example
#include<iostream> using namespace std; int maximum(int a, int b){ return (a>b)?a:b; } int maximum_sum_incr_subarr(int array[] , int n) { int max_sum = 0; int current_sum = array[0] ; for (int i=1; i<n ; i++ ) { if (array[i-1] < array[i]) current_sum = current_sum + array[i]; else { max_sum = maximum(max_sum, current_sum); current_sum = array[i]; } } return max(max_sum, current_sum); } int main() { int arr[] = {1, 2, 3, 2, 5, 1, 7}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Maximum sum : " << maximum_sum_incr_subarr(arr , n); }
Output
Maximum sum : 8
Advertisements