diff --git a/algorithms/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp b/algorithms/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp index e6bc986b1..f10321f86 100644 --- a/algorithms/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp +++ b/algorithms/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp @@ -25,28 +25,13 @@ class Solution { // Notes: // Some people think find the highest-price & lowest-price, this is wrong. // Because the highest-price must be after lowest-price - // int maxProfit(vector &prices) { - - int max=0, begin=0, end=0, delta=0; - + if(prices.size() == 0) return 0; + int MAX=0, MIN=prices[0]; for (int i=0; i max ){ - max = delta; - } - + MIN = min(MIN, prices[i]); + MAX = max(MAX, prices[i] - MIN); } - - return max; - + return MAX; } }; diff --git a/algorithms/kthSmallestElementInaBST/KthSmallestElementInABst.cpp b/algorithms/kthSmallestElementInaBST/KthSmallestElementInABst.cpp index fd3581b50..15f450cb3 100644 --- a/algorithms/kthSmallestElementInaBST/KthSmallestElementInABst.cpp +++ b/algorithms/kthSmallestElementInaBST/KthSmallestElementInABst.cpp @@ -49,20 +49,17 @@ class Solution { // in-order travel - non-recursive way int kthSmallestHelper_nonRecursive(TreeNode* root, int k){ stack s; - while(!s.empty() || root){ - - while (root) { + if(root){ s.push(root); - root = root->left; + root = root -> left; + }else{ + root = s.top(); + s.pop(); + k--; + if(k==0) return root -> val; + root = root -> right; } - - k--; - root = s.top()->right; - - if (k==0) return s.top()->val; - - s.pop(); } return -1; }