publicvoidmaxSubAry(int[] nums){ int max = nums[0], sum = 0; for (int num: nums) { sum = sum > 0 ? sum + num : num; max = Math.max(sum, max); } System.out.println(max); }
publicstaticvoidmain(String[] args){ Scanner sc = new Scanner(System.in); int length = sc.nextInt(); int nums[] = newint[length]; for (int i = 0; i < length; i++){ nums[i] = Integer.parseInt(sc.next()); } Main main = new Main(); main.maxSubAry(nums); sc.close(); } }
publicvoidmaxSubAry(int[] nums){ int max = Integer.MIN_VALUE; for(int i = 0; i < nums.length; i++){ int sum = 0; for(int j = i; j < nums.length; j++){ sum += nums[j]; if(max < sum) max = sum; } } System.out.println(max); }
publicstaticvoidmain(String[] args){ Scanner sc = new Scanner(System.in); int length = sc.nextInt(); int nums[] = newint[length]; for (int i = 0; i < length; i++){ nums[i] = Integer.parseInt(sc.next()); } Main main = new Main(); main.maxSubAry(nums); sc.close(); } }
publicvoidmaxSubAry(int[] nums){ int max = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++){ for( int j = i; j < nums.length; j++){ int sum = 0; for(int k = i; k <= j; k++){ sum += nums[k]; } if (sum > max) max = sum; } } System.out.println(max); }
publicstaticvoidmain(String[] args){ Scanner sc = new Scanner(System.in); int length = sc.nextInt(); int nums[] = newint[length]; for (int i = 0; i < length; i++){ nums[i] = Integer.parseInt(sc.next()); } Main main = new Main(); main.maxSubAry(nums); sc.close(); } }