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

Kedan's algorithm.java #2897

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
39 changes: 39 additions & 0 deletions Kedan's algorithm.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//basic driver code for test cases
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();

// Test case 1
int[] nums1 = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println("Max subarray sum for nums1: " + solution.maxSubArray(nums1)); // Expected output: 6

// Test case 2
int[] nums2 = {1};
System.out.println("Max subarray sum for nums2: " + solution.maxSubArray(nums2)); // Expected output: 1

// Test case 3
int[] nums3 = {5, 4, -1, 7, 8};
System.out.println("Max subarray sum for nums3: " + solution.maxSubArray(nums3)); // Expected output: 23

// Test case 4
int[] nums4 = {-1, -2, -3, -4};
System.out.println("Max subarray sum for nums4: " + solution.maxSubArray(nums4)); // Expected output: -1
}
}

// main code using Kedan's Algorithm
class Solution {
public int maxSubArray(int[] nums) {
int sum=0;
int ans=nums[0];

for(int i=0;i<nums.length;i++){
sum+=nums[i];
ans=Math.max(ans,sum);
if(sum<0){
sum=0;
}
}
return ans;
}
}