fork download
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4. public static int maxSubarraySum(int[] b) {
  5. int n = b.length - 1;
  6. if (n == 0) return 0;
  7.  
  8. int[] p1 = new int[n + 1];
  9. int maxSum = 0;
  10.  
  11. for (int i = 1; i <= n; ++i) {
  12. p1[i] = Math.max(Math.max(p1[i - 1] + b[i], b[i]), 0);
  13. maxSum = Math.max(maxSum, p1[i]);
  14. }
  15.  
  16. return maxSum;
  17. }
  18.  
  19.  
  20. public static void main(String[] args) {
  21. Scanner scanner = new Scanner(System.in);
  22.  
  23. int n = scanner.nextInt();
  24. int[] b = new int[n + 1]; // Adjust for 1-based indexing
  25.  
  26. for (int i = 1; i <= n; ++i) {
  27. b[i] = scanner.nextInt();
  28. }
  29.  
  30. int result = maxSubarraySum(b);
  31. System.out.println("Maximum subarray sum is " + result);
  32. }
  33. }
  34.  
Success #stdin #stdout 0.16s 58932KB
stdin
5
-2 1 -3 4 -1
stdout
Maximum subarray sum is 4