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