Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kadane's Algorithm #33

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Algo/KMPStringMatching.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

public class KMP {

public static void main(String[] args) {
String s = "ABCMNBCJDMVBC";
String pat = "BC";

int n = s.length();
int m = pat.length();
int[] lps = getLps(pat, m);
int i=0; int j=0;
while(i<n && j<m) {
if(s.charAt(i)==pat.charAt(j)) {
i++; j++;
}
if(j==m) {
System.out.println("found pattern at =" + (i-j));
j = lps[j-1];
}

if(i<n && j<m && s.charAt(i) != pat.charAt(j)) {
if(j != 0)
j = lps[j-1];
else
i++;
}
}
}

public static int[] getLps(String pat, int m) {
int[] lps = new int[m];
int i=1, len=0;
lps[0] = 0;
while (i<m) {
if(pat.charAt(i)==pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}else {
if(len > 0)
len = lps[len-1];
else{
lps[i] = len;
i++;
}
}
}
return lps;

}
}
27 changes: 27 additions & 0 deletions Algo/KadaneLargestSumConitnuousSubarray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import java.io.*;
import java.util.*;

class KadaneLargestSumConitnuousSubarray
{
public static void main (String[] args)
{
int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};
System.out.println("Maximum contiguous sum is " + maxSubArraySum(a));
}

static int maxSubArraySum(int arr[])
{
int size = arr.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;

for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
}