From 183a3a660ea4471b84118bdc8f774b3ae6912085 Mon Sep 17 00:00:00 2001 From: Aayush Jain Date: Sat, 10 Apr 2021 01:08:44 +0530 Subject: [PATCH] Add Kadane's Algorithm to Java (#149) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Kadane’s Algorithm * Update README.md * Kadane's Algorithm --- arrays/README.md | 1 + arrays/java/Kadanes_Algorithm.java | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 arrays/java/Kadanes_Algorithm.java diff --git a/arrays/README.md b/arrays/README.md index cb320b45..2120f48a 100644 --- a/arrays/README.md +++ b/arrays/README.md @@ -19,3 +19,4 @@ ### Java 1. [Counting Inversions](java/count-inversions.java) +2. [Kadane's Algorithm](java/Kadanes_Algorithm.java) diff --git a/arrays/java/Kadanes_Algorithm.java b/arrays/java/Kadanes_Algorithm.java new file mode 100644 index 00000000..01021467 --- /dev/null +++ b/arrays/java/Kadanes_Algorithm.java @@ -0,0 +1,30 @@ +// Java program to print largest contiguous array sum + +import java.io.*; +import java.util.*; + +class Kadane +{ + 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 a[]) + { + int size = a.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 + a[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; + } +}