classSolution { public: intmctFromLeafValues(vector<int>& arr){ int res = 0; stack<int> stk; for (int x : arr) { while (!stk.empty() && stk.top() <= x) { int y = stk.top(); stk.pop(); if (stk.empty() || stk.top() > x) { res += y * x; } else { res += stk.top() * y; } } stk.push(x); } while (stk.size() >= 2) { int x = stk.top(); stk.pop(); res += stk.top() * x; } return res; } };
publicclassSolution { publicintMctFromLeafValues(int[] arr) { int res = 0; Stack<int> stk = new Stack<int>(); foreach (int x in arr) { while (stk.Count > 0 && stk.Peek() <= x) { int y = stk.Pop(); if (stk.Count == 0 || stk.Peek() > x) { res += y * x; } else { res += stk.Peek() * y; } } stk.Push(x); } while (stk.Count >= 2) { int x = stk.Pop(); res += stk.Peek() * x; } return res; } }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defmctFromLeafValues(self, arr: List[int]) -> int: res = 0 stack = [] for x in arr: while stack and stack[-1] <= x: y = stack.pop() ifnot stack or stack[-1] > x: res += y * x else: res += stack[-1] * y stack.append(x) whilelen(stack) >= 2: x = stack.pop() res += stack[-1] * x return res
var mctFromLeafValues = function(arr) { let res = 0; let stack = []; for (let x of arr) { while (stack.length && stack[stack.length - 1] <= x) { let y = stack.pop(); if (!stack.length || stack[stack.length - 1] > x) { res += y * x; } else { res += stack[stack.length - 1] * y; } } stack.push(x); } while (stack.length >= 2) { let x = stack.pop(); res += stack[stack.length - 1] * x; } return res; }
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcmctFromLeafValues(arr []int)int { res, stk := 0, []int{} for _, x := range arr { forlen(stk) > 0 && stk[len(stk) - 1] <= x { iflen(stk) == 1 || stk[len(stk) - 2] > x { res += stk[len(stk) - 1] * x } else { res += stk[len(stk) - 2] * stk[len(stk) - 1] } stk = stk[:len(stk)-1] } stk = append(stk, x) } forlen(stk) > 1 { res += stk[len(stk) - 2] * stk[len(stk) - 1] stk = stk[:len(stk)-1] } return res }
intmctFromLeafValues(int* arr, int arrSize) { int res = 0; intstack[arrSize]; int top = 0; for (int i = 0; i < arrSize; i++) { int x = arr[i]; while (top > 0 && stack[top - 1] <= x) { int y = stack[top - 1]; top--; if (top == 0 || stack[top - 1] > x) { res += y * x; } else { res += stack[top - 1] * y; } } stack[top++] = x; } while (top >= 2) { int x = stack[top - 1]; top--; res += stack[top - 1] * x; } return res; }
复杂度分析
时间复杂度:O(n),其中 n 为数组 arr 的长度。每次循环都有入栈或出栈操作,总次数不超过 2 \times n,因此时间复杂度为 O(n)。