1
- package com .thealgorithms .dynamicprogramming ;
1
+ /** Author : Siddhant Swarup Mallick
2
+ * Github : https://github.com/siddhant2002
3
+ */
2
4
3
- import java .util .Scanner ;
5
+ /** Program description - To find the maximum subarray sum */
6
+ package com .thealgorithms .dynamicprogramming ;
4
7
5
- /**
6
- * Program to implement Kadane’s Algorithm to calculate maximum contiguous
7
- * subarray sum of an array Time Complexity: O(n)
8
- *
9
- * @author Nishita Aggarwal
10
- */
11
8
public class KadaneAlgorithm {
12
-
13
- /**
14
- * This method implements Kadane's Algorithm
15
- *
16
- * @param arr The input array
17
- * @return The maximum contiguous subarray sum of the array
18
- */
19
- static int largestContiguousSum (int arr []) {
20
- int i , len = arr .length , cursum = 0 , maxsum = Integer .MIN_VALUE ;
21
- if (len == 0 ) // empty array
9
+ public static boolean max_Sum (int a [] , int predicted_answer )
10
+ {
11
+ int sum =a [0 ],running_sum =0 ;
12
+ for (int k :a )
22
13
{
23
- return 0 ;
14
+ running_sum =running_sum +k ;
15
+ // running sum of all the indexs are stored
16
+ sum =Math .max (sum ,running_sum );
17
+ // the max is stored inorder to the get the maximum sum
18
+ if (running_sum <0 )
19
+ running_sum =0 ;
20
+ // if running sum is negative then it is initialized to zero
24
21
}
25
- for (i = 0 ; i < len ; i ++) {
26
- cursum += arr [i ];
27
- if (cursum > maxsum ) {
28
- maxsum = cursum ;
29
- }
30
- if (cursum <= 0 ) {
31
- cursum = 0 ;
32
- }
33
- }
34
- return maxsum ;
22
+ // for-each loop is used to iterate over the array and find the maximum subarray sum
23
+ return sum ==predicted_answer ;
24
+ // It returns true if sum and predicted answer matches
25
+ // The predicted answer is the answer itself. So it always return true
35
26
}
36
-
37
27
/**
38
- * Main method
39
- *
40
- * @param args Command line arguments
28
+ * OUTPUT :
29
+ * Input - {89,56,98,123,26,75,12,40,39,68,91}
30
+ * Output: it returns either true or false
31
+ * 1st approach Time Complexity : O(n)
32
+ * Auxiliary Space Complexity : O(1)
41
33
*/
42
- public static void main (String [] args ) {
43
- Scanner sc = new Scanner (System .in );
44
- int n , arr [], i ;
45
- n = sc .nextInt ();
46
- arr = new int [n ];
47
- for (i = 0 ; i < n ; i ++) {
48
- arr [i ] = sc .nextInt ();
49
- }
50
- int maxContSum = largestContiguousSum (arr );
51
- System .out .println (maxContSum );
52
- sc .close ();
53
- }
54
- }
34
+ }
0 commit comments