-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSubArray.java
More file actions
61 lines (51 loc) · 1.74 KB
/
Copy pathMaxSubArray.java
File metadata and controls
61 lines (51 loc) · 1.74 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class MaxSubArray {
public static void main(String[] args) {
testSingleElementArray();
testAllPositiveNumbers();
testAllNegativeNumbers();
testMixedNumbers();
testArrayWithZeros();
}
public static int solution(int[] nums) {
int max = nums[0];
int curr = nums[0];
for (int i = 1; i < nums.length; i++) {
curr = Math.max(nums[i], curr + nums[i]);
if (curr > max) {
max = curr;
}
}
return max;
}
// Test cases
public static void testSingleElementArray() {
int[] nums = {5};
int expected = 5;
int result = solution(nums);
System.out.println("Test Single Element Array: " + (result == expected));
}
public static void testAllPositiveNumbers() {
int[] nums = {1, 2, 3, 4, 5};
int expected = 15;
int result = solution(nums);
System.out.println("Test All Positive Numbers: " + (result == expected));
}
public static void testAllNegativeNumbers() {
int[] nums = {-1, -2, -3, -4, -5};
int expected = -1;
int result = solution(nums);
System.out.println("Test All Negative Numbers: " + (result == expected));
}
public static void testMixedNumbers() {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int expected = 6;
int result = solution(nums);
System.out.println("Test Mixed Numbers: " + (result == expected));
}
public static void testArrayWithZeros() {
int[] nums = {0, -3, 1, 1, -1, 2, -1, 3, -5, 4};
int expected = 5;
int result = solution(nums);
System.out.println("Test Array with Zeros: " + (result == expected));
}
}