-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKadane_Algorithm.cpp
More file actions
57 lines (54 loc) · 1.25 KB
/
Kadane_Algorithm.cpp
File metadata and controls
57 lines (54 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <bits/stdc++.h>
using namespace std;
void printArray(int arr[], int n)
{
int i = 0;
cout << "ARRAY THUS FORMED IS : ";
while (i < n)
{
cout << arr[i++] << " ";
}
}
void kadaneAlgorithm(int arr[], int n)
{
//*****************BRUTEFORCE METHOD NOT OPTIMISED**************
// int sum = 0;
// int max = sum;
// for (int i = 0; i < n; i++)
// { sum=0;
// for (int j = i; j < n; j++)
// {
// sum+=arr[j];
// if(sum>max)
// max=sum;
// }
// }
// cout << endl
// << "MAXIMUM SUM OF CONTIGOUS SUBARRAY IS : " << max;
//======================BEST SOLUTION OPTIMISED================
int sum = 0; //it may be assigned =0 || INT_MIN
int maximum = arr[0];
for (int i = 0; i < n; i++)
{
sum += arr[i];
maximum = max(maximum, sum);
if (sum < 0)
sum = 0;
}
cout << endl
<< "MAXIMUM SUM OF CONTIGOUS SUBARRAY IS : " << maximum;
}
int main()
{
int n, i = 0;
cout << "Enter the number of Elements : ";
cin >> n;
int arr[n];
cout << "Enter the Elements : ";
while (i < n)
{
cin >> arr[i++];
}
printArray(arr, n);
kadaneAlgorithm(arr, n-1);
}