|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N; |
| 7 | + static String expression; |
| 8 | + static int maxResult = Integer.MIN_VALUE; |
| 9 | + |
| 10 | + public static void main(String[] args) throws IOException { |
| 11 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + N = Integer.parseInt(br.readLine()); |
| 13 | + expression = br.readLine(); |
| 14 | + |
| 15 | + if (N == 1) { |
| 16 | + System.out.println(expression.charAt(0) - '0'); |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + dfs(0, expression.charAt(0) - '0'); |
| 21 | + System.out.println(maxResult); |
| 22 | + } |
| 23 | + |
| 24 | + static void dfs(int idx, int currentValue) { |
| 25 | + if (idx >= N - 1) { |
| 26 | + maxResult = Math.max(maxResult, currentValue); |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + char operator = expression.charAt(idx + 1); |
| 31 | + int nextNum = expression.charAt(idx + 2) - '0'; |
| 32 | + |
| 33 | + int nextValue = calculate(currentValue, operator, nextNum); |
| 34 | + dfs(idx + 2, nextValue); |
| 35 | + |
| 36 | + if (idx + 4 < N) { |
| 37 | + char nextOperator = expression.charAt(idx + 3); |
| 38 | + int nextNextNum = expression.charAt(idx + 4) - '0'; |
| 39 | + |
| 40 | + int bracketResult = calculate(nextNum, nextOperator, nextNextNum); |
| 41 | + int resultWithBracket = calculate(currentValue, operator, bracketResult); |
| 42 | + dfs(idx + 4, resultWithBracket); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + static int calculate(int a, char operator, int b) { |
| 47 | + switch (operator) { |
| 48 | + case '+': return a + b; |
| 49 | + case '-': return a - b; |
| 50 | + case '*': return a * b; |
| 51 | + default: return 0; |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | +``` |
0 commit comments