forked from JaeYeopHan/algorithm_basic_java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindMaxSumInArray.java
42 lines (33 loc) · 1002 Bytes
/
FindMaxSumInArray.java
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
package exercise;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class FindMaxSumInArray {
/*
TASK
주어진 배열에서 합이 최대가 되는 sub array의 합을 구한다.
*/
@Test
public void test() {
int[] arr1 = {1,2,-9,4,-3,12,24,3,4,-8,10,9};
assertThat(solution(arr1), is(55));
int[] arr2 = {};
assertThat(solution(arr2), is(Integer.MAX_VALUE));
int[] arr3 = {1};
assertThat(solution(arr3), is(1));
int[] arr4 = {1,2};
assertThat(solution(arr4), is(3));
}
public int solution(int[] arr) {
if (arr == null || arr.length == 0) return Integer.MAX_VALUE;
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max + arr[i]) {
max = arr[i];
} else {
max += arr[i];
}
}
return max;
}
}