-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSumSubarraySlidingWindow.java
More file actions
47 lines (37 loc) · 1.25 KB
/
Copy pathMaxSumSubarraySlidingWindow.java
File metadata and controls
47 lines (37 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Arrays;
import java.util.Scanner;
class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
}
public class MaxSumSubarraySlidingWindow {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Solution solution = new Solution();
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
if (n <= 0) {
System.out.println("The array must contain at least one element.");
scanner.close();
return;
}
int[] nums = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
System.out.println("Input: " + Arrays.toString(nums));
System.out.println("Output: " + solution.maxSubArray(nums));
scanner.close();
}
}