Skip to content

Commit 690be8b

Browse files
committed
smallest sum contiguous subarray solution added
1 parent 553b8b5 commit 690be8b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// C++ implementation to find the smallest sum
2+
// contiguous subarray
3+
#include <bits/stdc++.h>
4+
5+
using namespace std;
6+
7+
// function to find the smallest sum contiguous subarray
8+
int smallestSumSubarr(int arr[], int n)
9+
{
10+
// to store the minimum value that is ending
11+
// up to the current index
12+
int min_ending_here = INT_MAX;
13+
14+
// to store the minimum value encountered so far
15+
int min_so_far = INT_MAX;
16+
17+
// traverse the array elements
18+
for (int i=0; i<n; i++)
19+
{
20+
// if min_ending_here > 0, then it could not possibly
21+
// contribute to the minimum sum further
22+
if (min_ending_here > 0)
23+
min_ending_here = arr[i];
24+
25+
// else add the value arr[i] to min_ending_here
26+
else
27+
min_ending_here += arr[i];
28+
29+
// update min_so_far
30+
min_so_far = min(min_so_far, min_ending_here);
31+
}
32+
33+
// required smallest sum contiguous subarray value
34+
return min_so_far;
35+
}
36+
37+
38+
// Driver program to test above
39+
int main()
40+
{
41+
int arr[] = {3, -4, 2, -3, -1, 7, -5};
42+
int n = sizeof(arr) / sizeof(arr[0]);
43+
cout << "Smallest sum: "
44+
<< smallestSumSubarr(arr, n);
45+
return 0;
46+
}

0 commit comments

Comments
 (0)