|
| 1 | +/** |
| 2 | + * 2019. The Score of Students Solving Math Expression |
| 3 | + * https://leetcode.com/problems/the-score-of-students-solving-math-expression/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a string s that contains digits 0-9, addition symbols '+', and multiplication |
| 7 | + * symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). |
| 8 | + * This expression was given to n elementary school students. The students were instructed to |
| 9 | + * get the answer of the expression by following this order of operations: |
| 10 | + * 1. Compute multiplication, reading from left to right; Then, |
| 11 | + * 2. Compute addition, reading from left to right. |
| 12 | + * |
| 13 | + * You are given an integer array answers of length n, which are the submitted answers of the |
| 14 | + * students in no particular order. You are asked to grade the answers, by following these rules: |
| 15 | + * - If an answer equals the correct answer of the expression, this student will be rewarded |
| 16 | + * 5 points; |
| 17 | + * - Otherwise, if the answer could be interpreted as if the student applied the operators in |
| 18 | + * the wrong order but had correct arithmetic, this student will be rewarded 2 points; |
| 19 | + * - Otherwise, this student will be rewarded 0 points. |
| 20 | + * |
| 21 | + * Return the sum of the points of the students. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {string} s |
| 26 | + * @param {number[]} answers |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var scoreOfStudents = function(s, answers) { |
| 30 | + const correct = eval(s.replace(/(\d)([*+])/g, '$1 $2 ')); |
| 31 | + |
| 32 | + const n = s.length; |
| 33 | + const dp = new Map(); |
| 34 | + |
| 35 | + function compute(start, end) { |
| 36 | + const key = `${start},${end}`; |
| 37 | + if (dp.has(key)) return dp.get(key); |
| 38 | + |
| 39 | + const results = new Set(); |
| 40 | + if (start === end) { |
| 41 | + results.add(Number(s[start])); |
| 42 | + dp.set(key, results); |
| 43 | + return results; |
| 44 | + } |
| 45 | + |
| 46 | + for (let i = start + 1; i < end; i += 2) { |
| 47 | + const leftResults = compute(start, i - 1); |
| 48 | + const rightResults = compute(i + 1, end); |
| 49 | + const op = s[i]; |
| 50 | + |
| 51 | + for (const left of leftResults) { |
| 52 | + for (const right of rightResults) { |
| 53 | + const val = op === '+' ? left + right : left * right; |
| 54 | + if (val <= 1000) results.add(val); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + dp.set(key, results); |
| 60 | + return results; |
| 61 | + } |
| 62 | + |
| 63 | + const wrongAnswers = compute(0, n - 1); |
| 64 | + let result = 0; |
| 65 | + |
| 66 | + for (const answer of answers) { |
| 67 | + if (answer === correct) result += 5; |
| 68 | + else if (wrongAnswers.has(answer)) result += 2; |
| 69 | + } |
| 70 | + |
| 71 | + return result; |
| 72 | +}; |
0 commit comments