Last active
October 20, 2016 16:45
-
-
Save hadielmougy/39b0f47e753d98f9691a78fce03fadf0 to your computer and use it in GitHub Desktop.
maximum subarray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.algorithms; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.Scanner; | |
import static java.lang.Math.*; | |
import static java.util.Arrays.*; | |
import static java.util.stream.IntStream.*; | |
/** | |
* Created by Hadi on 10/20/2016. | |
*/ | |
public class Solution { | |
public static void main(String[] args){ | |
System.out.println(arr(new int[]{3, -2, -3, 1, 4, 5,2})[0]); | |
} | |
private static int[] arr(int[] a) { | |
if(stream(a).allMatch(x->x<0)){ | |
int m = stream(a).max().getAsInt(); | |
return new int[]{m,m}; | |
} | |
int[] res = new int[2]; | |
int ans = 0; | |
int sum = 0; | |
for (int i = 0; i < a.length; i++) { | |
sum = max(sum + a[i], 0); | |
ans = max(ans, sum); | |
if(ans <0) ans = 0; | |
} | |
res[0] = ans; | |
res[1] = stream(a).filter(x -> x>0).sum(); | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment