Posted onEdited onInLeetCodeDisqus: Symbols count in article: 202Reading time ≈1 mins.
dp O(n) time O(1) space
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intmaxSubArray(vector<int>& nums){ int f = 0, res = INT_MIN; for (int x : nums) { f = max(f, 0) + x; res = max(res, f); } return res; } };
classMovingAverage { public: /** Initialize your data structure here. */ MovingAverage(int size) : n(size), sum(0) {
}
doublenext(int val){ q.push(val); sum += val; if (q.size() > n) { sum -= q.front(); q.pop(); } return sum / q.size(); // 切记不能除n!!!因为queue里不一定有n个数 }
int n; double sum; queue<int> q; };
/** * Your MovingAverage object will be instantiated and called as such: * MovingAverage* obj = new MovingAverage(size); * double param_1 = obj->next(val); */
intdfs(TreeNode *root, int depth){ // depth是从根到当前结点的深度,返回当前这棵树的深度 if (!root) return0; int l = dfs(root->left, depth + 1); // 子树的深度 int r = dfs(root->right, depth + 1); if (l == r && depth + l >= mx) { // find the lowest root that covers all the deepest leaves mx = depth + l; res = root; } return max(l, r) + 1; }
intdfs(TreeNode *root, int depth){ // depth是从根到当前结点的深度,返回当前这棵树的深度 if (!root) return0; int l = dfs(root->left, depth + 1); // 子树的深度 int r = dfs(root->right, depth + 1); if (l == r && depth + l >= mx) { // find the lowest root that covers all the deepest leaves mx = depth + l; res = root; } return max(l, r) + 1; }