diff --git a/C++/Kadane's_Algorithm.cpp b/C++/Kadane's_Algorithm.cpp new file mode 100644 index 00000000..7f21f5db --- /dev/null +++ b/C++/Kadane's_Algorithm.cpp @@ -0,0 +1,110 @@ +// KADANE'S ALGORITHM + +// Why Kadane’s Algorithm ? +// It is used to find out the maximum subarray sum from an array of integers. + +// Two methods to find the maximum subarray sum is +// 1. The brute force method +// 2. Kadane’s algorithm + +// Kadane’s algorithm is an iterative dynamic programming algorithm. It uses optimal sub-structures. By this, we mean that to calculate the maximum subarray ending at a particular position, we use a related, smaller subproblem (the maximum subarray ending at the previous position). Because of this, it is dynamic programming. Kadane’s algorithm uses a greedy and dynamic approach. + + +// -> BRUTE FORCE CODE (C++): + + #include + using namespace std; + + void maxSumSubarray(int arr[], int n){ + vector ans; + + //choosing the starting point of subarray + for(int i=0; i>t; + while(t--){ + int n; + cin>>n; + int arr[n]; + for(int i=0; i>arr[i]; + } + maxSumSubarray(arr, n); + } + return 0; + } + + +// -> KADANE ALGORITHM CODE (C++): + + #include + using namespace std; + + int kadaneAlgorithm(int arr[], int n){ + //stores the maximum sum subarray sum found so far + + int max_so_far = 0; + + //stores the maximum sum of subarray at the current position + + int max_ending_here = 0; + + for (int i = 0; i < n; i++){ + // adding the current element to maximum sum ending at previous index i-1 + + max_ending_here = max_ending_here + arr[i]; + + // this helps in avoiding getting any negative sum + + if(max_ending_here < 0) + max_ending_here = 0; + + // getting the maximum sum in result by finding out the maximum from max_so_far and max_ending_here + + if(max_so_far < max_ending_here) + max_so_far = max_ending_here; + } + + return max_so_far; + } + + int main() { + int t; + cin>>t; + while(t--){ + int n; + cin>>n; + int arr[n]; + for(int i=0; i < n; i++){ + cin>>arr[i]; + } + cout <<"Maximum sum of contiguous subarray is: "< +#include + +int main() +{ + int a[10][10], b[10][10], mul[10][10], r, c, i, j, k; + printf("Enter the number of rows: "); + scanf("%d", &r); + printf("Enter the number of columns: "); + scanf("%d", &c); + printf("Enter the elements in first matrix:\n"); + for (i = 0; i < r; i++) + { + for (j = 0; j < c; j++) + { + scanf("%d", &a[i][j]); + } + } + printf("\nEnter the elements in second matrix:\n"); + for (i = 0; i < r; i++) + { + for (j = 0; j < c; j++) + { + scanf("%d", &b[i][j]); + } + } + + printf("\nMultiplication of two matrices is:\n"); + for (i = 0; i < r; i++) + { + for (j = 0; j < c; j++) + { + mul[i][j] = 0; + for (k = 0; k < c; k++) + { + mul[i][j] += a[i][k] * b[k][j]; + } + } + } + //for printing result + for (i = 0; i < r; i++) + { + for (j = 0; j < c; j++) + { + printf("%d\t", mul[i][j]); + } + printf("\n"); + } + return 0; +} \ No newline at end of file