|
| 1 | +/* Name : Aneesh |
| 2 | +Github username : 007aneesh |
| 3 | +Repository name : data-structures-and-algorithms |
| 4 | +Problem : Kadane's algorithm in Java |
| 5 | +Issue Number : #1180 |
| 6 | +Problem statement : Given an integer array nums, find the subarray with the largest sum, and return its sum. |
| 7 | +
|
| 8 | +Sample testcases: |
| 9 | +
|
| 10 | +Testcase 1 --> |
| 11 | +
|
| 12 | +Input: number of elements in array = 9 |
| 13 | +nums = [-2,1,-3,4,-1,2,1,-5,4] |
| 14 | +Output: 6 |
| 15 | +
|
| 16 | +Testcase 2 --> |
| 17 | +Input: number of elements in array |
| 18 | +nums = [5,4,-1,7,8] |
| 19 | +Output: 23 |
| 20 | +
|
| 21 | +Time Complexity = O(n) |
| 22 | +Space Complexity = O(1) |
| 23 | +
|
| 24 | +
|
| 25 | +Explanation: |
| 26 | +This code asks the user to enter the number of elements in an array, |
| 27 | +and then prompts them to enter each element of the array one at a time. |
| 28 | +Once the array is complete, the code applies the Kadane's algorithm to |
| 29 | +find the maximum sum of any subarray within the array, and then prints |
| 30 | +the result to the console. |
| 31 | +
|
| 32 | +Kadane's algorithm is a way of finding the maximum sum of a contiguous subarray within an array, |
| 33 | +and it does so by keeping track of the maximum sum seen so far as it iterates through the array. |
| 34 | +At each step, it adds the current element to a running sum, and if that sum becomes negative, |
| 35 | +it resets the running sum to zero. If the running sum is ever greater than the maximum seen so far, |
| 36 | +it updates the maximum. Finally, it returns the maximum sum. |
| 37 | +*/ |
| 38 | + |
| 39 | +// ----------------------------------------------------------------------------- code begins now! |
| 40 | +import java.util.Scanner; |
| 41 | + |
| 42 | +public class kadanes_algo { |
| 43 | + public static int maxSubArraySum(int[] arr) { |
| 44 | + if (arr == null || arr.length == 0) { |
| 45 | + return 0; |
| 46 | + } |
| 47 | + |
| 48 | + int max = 0; |
| 49 | + int sum = Integer.MIN_VALUE; |
| 50 | + |
| 51 | + for (int i = 0; i < arr.length; i++) { |
| 52 | + max += arr[i]; |
| 53 | + |
| 54 | + if (max < arr[i]) { |
| 55 | + max = arr[i]; |
| 56 | + } |
| 57 | + |
| 58 | + if (sum < max) { |
| 59 | + sum = max; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return sum; |
| 64 | + } |
| 65 | + |
| 66 | + public static void main(String[] args) { |
| 67 | + Scanner sc = new Scanner(System.in); |
| 68 | + System.out.print("Enter the number of elements in the array: "); |
| 69 | + int n = sc.nextInt(); |
| 70 | + int[] arr = new int[n]; |
| 71 | + System.out.println("Enter the elements of the array:"); |
| 72 | + for (int i = 0; i < n; i++) { |
| 73 | + arr[i] = sc.nextInt(); |
| 74 | + } |
| 75 | + |
| 76 | + int maxSum = maxSubArraySum(arr); |
| 77 | + System.out.println("The maximum subarray sum is " + maxSum); |
| 78 | + } |
| 79 | + |
| 80 | +} |
0 commit comments