Datawhale-LeetCode编程实践组队学习Task10

121. 买卖股票的最佳时机

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        // int n = prices.size();
        // if(n == 0 || n == 1)
        //     return 0;
        // vector<int> dp(n + 1);
        // int ans = prices[1] - prices[0];
        // dp[1] = 0;
        // for(int i = 2; i < n; i++) {
        //     if(prices[i - 1] < prices[dp[i - 1]]) {
        //         dp[i] = i - 1;
        //     }
        //     else {
        //         dp[i] = dp[i - 1];
        //     }
        //     if(prices[i] - prices[dp[i]] > ans) {
        //         ans = prices[i] - prices[dp[i]];
        //     }
        // }
        // if(ans < 0) return 0;
        // return ans;
        int m = INT_MAX;
        int ans = 0;

        for (int x : prices)
        {
            m = min(m, x);
            ans = max(ans, x - m);
        }

        return ans;
    }
};

122. 买卖股票的最佳时机 II

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int i = 0;
        int ans = 0;
        // while (i < n - 1)
        // {
        //     while (i < n - 1 && prices[i] >= prices[i + 1]) i++;
        //     ans -= prices[i];
        //     while (i < n - 1 && prices[i] <= prices[i + 1]) i++;
        //     ans += prices[i];
        // }
        // return ans;
        for (; i < n - 1; ++i)
        {
            ans += max(0, prices[i + 1] - prices[i]);
        }
        return ans;
    }
};

124. 二叉树中的最大路径和

class Solution {
private:
    int maxSum = INT_MIN;

public:
    int maxGain(TreeNode* node) {
        if (node == nullptr) {
            return 0;
        }
        int leftGain = max(maxGain(node->left), 0);
        int rightGain = max(maxGain(node->right), 0);
        int priceNewpath = node->val + leftGain + rightGain;
        maxSum = max(maxSum, priceNewpath);
        return node->val + max(leftGain, rightGain);
    }

    int maxPathSum(TreeNode* root) {
        maxGain(root);
        return maxSum;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43627017/article/details/112975065
今日推荐