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

Modified code Largest Sum Contiguous Subarray [C, Java] #421

Closed
wants to merge 13 commits into from
26 changes: 26 additions & 0 deletions largest_sum_contiguous_subarray/LargestSumContiguousSubArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Implementation of famous dynamic programming problem
* Largest Sum Contiguous Subarray
* Kadane Algorithm
* Time complexity O(n)
*/

public class LargestSumContiguousSubArray {

public static int largestSumContiguousSubArray(int[] array) { // maximum sum method implemention
int prevSum = array[0]; // initialize current sum amd previous sum
int currentSum = array[0];
for (int i = 1; i < array.length; i++) {
currentSum += array[i]; // add values in current sum
currentSum = Math.max(currentSum, array[i]); // maximum from current sum and current array value
prevSum = Math.max(currentSum, prevSum); // maximum from current sum and previous sum
}
return prevSum;
}

public static void main(String[] args) {

int[] array = new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println("Largest Sum of Contiguous SubArray:" + "\t" + largestSumContiguousSubArray(array));
}
}
32 changes: 0 additions & 32 deletions largest_sum_contiguous_subarray/LargestSumContiguousSubarray.java

This file was deleted.

19 changes: 7 additions & 12 deletions largest_sum_contiguous_subarray/largestSumContiguousSubarray.c
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
#include <stdio.h>
#include <stdlib.h>
#define max(a,b) (((a)>(b)) ? (a) : (b))

int largestSumContinousSubArray(int arr[], int size) {
int largestSumContiguousSubarray(int arr[], int size) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jsroyal Sir please fix the function name as per C guidelines.

int max_till = 0;
int max_int = 0;
for (int i = 0; i < size; i++) {
max_int = max_int + arr[i];
if(max_till < max_int) {
max_till = max_int;
}
if (max_int < 0) {
max_int = 0;
}
max_int = max(max_int, arr[i]);
max_till = max(max_till, max_int);
}
return max_till;
}

int main() {
int array[10];
for (int k = 0; k < 10; k++) {
array[k] = rand() % 10;
}
printf("%d", largestSumContinousSubArray(array, 10));
int array[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4, 5};
int size = sizeof(array) / sizeof(array[0]);
printf("%d\n", largestSumContiguousSubarray(array, size));
}