Update Kadane's-Algorithm.cpp
parent
d3c2184af8
commit
2332f21991
|
@ -61,6 +61,21 @@ int max_subarray_sum_method_3(int arr[],int n)
|
||||||
}
|
}
|
||||||
return maxi;
|
return maxi;
|
||||||
}
|
}
|
||||||
|
// optimized version kadane's algo with one loop
|
||||||
|
long long max_subarray_sum_method_4 (int arr[],int n) { //used for long and big values or integers
|
||||||
|
long long sum,maxi=0; //declaring variables
|
||||||
|
for (int i=0; i<size; i++) {
|
||||||
|
maxi= maxi+arr[i];
|
||||||
|
if (sum<maxi) { //if maxSum is greater then maxElement then the maxSum == maxElement
|
||||||
|
sum=maxi;
|
||||||
|
}
|
||||||
|
else if (maxi<0) { //if elements in array is 0 then return 0
|
||||||
|
sum=0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cout<<"\nUsing Kadane's Algoritham maximum sum of subarray is: "<<sum;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
|
@ -75,8 +90,10 @@ int main()
|
||||||
int ans1=max_subarray_sum_method_1(arr,n);//this is brute force approach time complexity=O(n^3) || space complexity=O(1);
|
int ans1=max_subarray_sum_method_1(arr,n);//this is brute force approach time complexity=O(n^3) || space complexity=O(1);
|
||||||
int ans2=max_subarray_sum_method_2(arr,n);//this is optimized brute force approach time complexity=O(n^2) || space complexity=O(1);
|
int ans2=max_subarray_sum_method_2(arr,n);//this is optimized brute force approach time complexity=O(n^2) || space complexity=O(1);
|
||||||
int ans3=max_subarray_sum_method_3(arr,n);//this is further optimized approach called "Kadane's Algorithm" time complexity=O(n)|| space complexity=O(1);
|
int ans3=max_subarray_sum_method_3(arr,n);//this is further optimized approach called "Kadane's Algorithm" time complexity=O(n)|| space complexity=O(1);
|
||||||
|
int ans4=max_subarray_sum_method_4(arr,size);//this is optimized approach time complexity=O(n) || space complexity=O(1);
|
||||||
cout<<"max_subarray_sum:"<<ans1<<endl;
|
cout<<"max_subarray_sum:"<<ans1<<endl;
|
||||||
cout<<"max_subarray_sum:"<<ans2<<endl;
|
cout<<"max_subarray_sum:"<<ans2<<endl;
|
||||||
cout<<"max_subarray_sum:"<<ans3<<endl;//print any ans1,ans2,ans3;
|
cout<<"max_subarray_sum:"<<ans3<<endl;
|
||||||
|
cout<<"max_subarray_sum:"<<ans4<<endl; //print any ans1,ans2,ans3,ans4;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue