GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Kadane's Algorithm added · Yang-Dylan/Java@62fdf0d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Dynamic Programming
    • KadaneAlgorithm.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Dynamic Programming/KadaneAlgorithm.java‎

Copy file name to clipboard
+55Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.util.Scanner;
2+
3+
/**
4+
* Program to implement Kadane’s Algorithm to
5+
* calculate maximum contiguous subarray sum of an array
6+
* Time Complexity: O(n)
7+
*
8+
* @author Nishita Aggarwal
9+
*
10+
*/
11+
12+
public class KadaneAlgorithm {
13+
14+
/**
15+
* This method implements Kadane's Algorithm
16+
*
17+
* @param arr The input array
18+
* @return The maximum contiguous subarray sum of the array
19+
*
20+
*/
21+
static int largestContiguousSum(int arr[]){
22+
int i,len=arr.length,cursum=0,maxsum=Integer.MIN_VALUE;
23+
if(len==0) //empty array
24+
return 0;
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;
35+
}
36+
37+
/**
38+
* Main method
39+
*
40+
* @param args Command line arguments
41+
*/
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+
55+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.