Skip to content

Instantly share code, notes, and snippets.

@czxttkl
Last active December 31, 2015 03:39
Show Gist options
  • Save czxttkl/7929509 to your computer and use it in GitHub Desktop.
Save czxttkl/7929509 to your computer and use it in GitHub Desktop.
public class TestConSum {
public static void main(String... args) {
int[] arr = new int[]{-2,11,-4,13, -9, -10,99};
int negsum = 0;
int maxsum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
negsum += arr[i];
continue;
}
if (arr[i] > 0) {
maxsum = max(maxsum + negsum + arr[i], arr[i], maxsum);
negsum = 0;
}
}
System.out.println(maxsum);
}
private static int max (int a, int b, int c) {
int tmp = a > b? a : b;
return tmp > c? tmp : c;
}
}
@czxttkl
Copy link
Author

czxttkl commented Dec 13, 2013

Good question.
I suppose the result is 0.

Your post of max product for consecutive nums is awesome.

@wusuopubupt
Copy link

也是参考别人的代码做的“微创新”,^_^

@wusuopubupt
Copy link

阿瑆,你这个方法真的很好!!!

@buptpatriot
Copy link

{2, -3, 1}?

@buptpatriot
Copy link

public class Test {

public static void main(String... args) {

    int[] arr = new int[]{-2,11,-4,13,-5,-2};

    int maxsum = Integer.MIN_VALUE;
    int currentHeight = 0;
    int minHeight = 0;

    for (int i = 0; i < arr.length; i++) {
        currentHeight += arr[i];
        maxsum = Math.max(currentHeight - minHeight, maxsum);
        minHeight = Math.min(minHeight, currentHeight);
    }

    System.out.println(maxsum);
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment