Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 952275a

Browse filesBrowse files
committed
Add code to find max of sub array
1 parent 908af65 commit 952275a
Copy full SHA for 952275a

1 file changed

+42Lines changed: 42 additions & 0 deletions

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
Expand file treeCollapse file tree
Open diff view settings
Collapse file
+42Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package exercise;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.CoreMatchers.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
public class FindMaxSumInArray {
9+
10+
/*
11+
TASK
12+
주어진 배열에서 합이 최대가 되는 sub array의 합을 구한다.
13+
*/
14+
15+
@Test
16+
public void test() {
17+
int[] arr1 = {1,2,-9,4,-3,12,24,3,4,-8,10,9};
18+
assertThat(solution(arr1), is(55));
19+
int[] arr2 = {};
20+
assertThat(solution(arr2), is(Integer.MAX_VALUE));
21+
int[] arr3 = {1};
22+
assertThat(solution(arr3), is(1));
23+
int[] arr4 = {1,2};
24+
assertThat(solution(arr4), is(3));
25+
}
26+
27+
public int solution(int[] arr) {
28+
if (arr == null || arr.length == 0) return Integer.MAX_VALUE;
29+
30+
int max = arr[0];
31+
32+
for (int i = 1; i < arr.length; i++) {
33+
if (arr[i] > max + arr[i]) {
34+
max = arr[i];
35+
} else {
36+
max += arr[i];
37+
}
38+
}
39+
40+
return max;
41+
}
42+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.