Skip to content

Commit

Permalink
Merge pull request keshavsingh4522#526 from Bhavanak021/master
Browse files Browse the repository at this point in the history
Kadane's Alorithm
  • Loading branch information
keshavsingh4522 committed Oct 2, 2021
2 parents fef0fcd + 39cb747 commit 4ed9811
Show file tree
Hide file tree
Showing 2 changed files with 124 additions and 0 deletions.
76 changes: 76 additions & 0 deletions CPP/Data Structures/Trees/Binary Trees/TreeTraversal.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//TREE TRAVERSAL
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int data;
node* left;
node* right;
};

node* newNode(int key)
{
node* tmp = new node();
tmp->data = key;
tmp->left = tmp->right = nullptr;

return tmp;
}

//INSERTION
node* insert(node* root, int l_data){
if(root == nullptr){
return newNode(l_data);
}
if(l_data <= root->data){
root->left = insert(root->left, l_data);
}else{
root->right = insert(root->right, l_data);
}
return root;
}

//INORDER TRAVERSAL
void inorder(node* root){
if(root == nullptr){
return;
}
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}

//PREORDER TRAVERSAL
void preOrder(node* root){
if(root == nullptr){
return;
}
cout<<root->data<<" ";
preOrder(root->left);
preOrder(root->right);
}

//POSTORDER TRAVERSAL
void postOrder(node* root){
if(root == nullptr){
return;
}
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<" ";
}

int main(){
node *root = newNode(1);

root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout<<"\n Pre order transversal: ";
preOrder(root);
cout<<"\n Inorder transversal: ";
inorder(root);
cout<<"\n Post order transversal: ";
postOrder(root);
}
48 changes: 48 additions & 0 deletions DP/KadanesAlgorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
Kadane's Algorithm
Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number)
which has the maximum sum and return its sum.
Example 1:
Input:
N = 5
Arr[] = {1,2,3,-2,5}
Output:
9
Explanation:
Max subarray sum is 9
of elements (1, 2, 3, -2, 5) which
is a contiguous subarray.
Example 2:
Input:
N = 4
Arr[] = {-1,-2,-3,-4}
Output:
-1
Explanation:
Max subarray sum is -1
of element (-1)
*/
#include<iostream>
using namespace std;

int maxSum(int a[], int n){
int ma = INT_MIN;
int max_th = 0;
for(int i=0; i<n; i++){
max_th = max_th+ a[i];
if(max_th>ma)
ma = max_th;
if(max_th<0)
max_th = 0;
}
return ma;
}
int main(){
int n;
cin>>n;
int a[n];
for(int i=0; i<n; i++)
cin>>a[i];
int sum= maxSum(a, n);
cout<<"Sum: "<<sum;
}

0 comments on commit 4ed9811

Please sign in to comment.