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; // Adjust for 1-based indexing
  6. if (n == 0) return 0;
  7.  
  8. int T = 0; // Initialize T to 0, which will store the maximum sum subarray
  9. int prv = 0; // Initialize prv to 0, which will store the current maximum sum subarray ending at b[i]
  10.  
  11. for (int i = 1; i <= n; ++i) {
  12. int current = Math.max(prv + b[i], b[i]);
  13. current = Math.max(current, 0);
  14. prv = current;
  15. T = Math.max(T, current);
  16. }
  17.  
  18. return T;
  19. }
  20.  
  21. public static void main(String[] args) {
  22. Scanner scanner = new Scanner(System.in);
  23.  
  24. int n = scanner.nextInt();
  25. int[] b = new int[n + 1]; // Adjust for 1-based indexing
  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.21s 56904KB
stdin
1
5
stdout
Maximum subarray sum is 5