Skip to content

Commit a38de79

Browse files
committed
[2020kakao(intern)-p2] 수식 최대화
1 parent e90e6ec commit a38de79

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,3 +516,4 @@
516516
| # || Problem | Note |
517517
| :-: | :-: | :-------------------------------------------- | :--- |
518518
| 01 | | [키패드 누르기](./src/_2020_카카오_인턴십/P1) | |
519+
| 02 | | [수식 최대화](./src/_2020_카카오_인턴십/P2) | |
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package _2020_카카오_인턴십.P2;
2+
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
public static void main(String[] args) {
8+
Solution sol = new Solution();
9+
System.out.println(sol.solution("100-200*300-500+20")); // 60420
10+
System.out.println(sol.solution("50*6-3*2")); // 300
11+
}
12+
}
13+
14+
class Solution {
15+
16+
char[][] opCases = {
17+
{'+', '-', '*'},
18+
{'+', '*', '-'},
19+
{'-', '+', '*'},
20+
{'-', '*', '+'},
21+
{'*', '+', '-'},
22+
{'*', '-', '+'}
23+
};
24+
25+
public long solution(String expression) {
26+
27+
List<Long> numList = new ArrayList<>();
28+
List<Character> opList = new ArrayList<>();
29+
30+
int idx = 0, n = expression.length();
31+
while (idx < n) {
32+
StringBuilder num = new StringBuilder();
33+
while (idx < n && !isOp(expression.charAt(idx))) {
34+
num.append(expression.charAt(idx++));
35+
}
36+
numList.add(Long.parseLong(num.toString()));
37+
if (idx < n) opList.add(expression.charAt(idx++));
38+
}
39+
40+
long ans = 0;
41+
for (char[] op : opCases) {
42+
List<Long> nums = new ArrayList<>(numList);
43+
List<Character> ops = new ArrayList<>(opList);
44+
45+
for (int i = 0; i < 3; i++) {
46+
int ofs;
47+
while ((ofs = ops.indexOf(op[i])) >= 0) {
48+
nums.add(ofs, calc(op[i], nums.get(ofs), nums.get(ofs+1)));
49+
nums.remove(ofs+1);
50+
nums.remove(ofs+1);
51+
ops.remove(ofs);
52+
}
53+
}
54+
55+
ans = Math.max(ans, Math.abs(nums.get(0)));
56+
}
57+
58+
return ans;
59+
}
60+
61+
private boolean isOp(char c) {
62+
return c == '+' || c == '*' || c == '-';
63+
}
64+
65+
private long calc(char op, long a, long b) {
66+
if (op == '*') return a*b;
67+
else if (op == '+') return a+b;
68+
else return a-b;
69+
}
70+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
## [2020 카카오 인턴십] 수식 최대화
2+
3+
![image](https://user-images.githubusercontent.com/22045163/116247404-c74bad00-a7a5-11eb-8f81-d1931eae7898.png)

0 commit comments

Comments
 (0)