思路:
- class Solution {
- public:
- int rob(TreeNode* root) {
- vector<int>res=judge(root);
- return res[0]>res[1]?res[0]:res[1];
- }
-
- vector<int> judge(TreeNode*root){
- if(root==nullptr) return {0,0};
-
- vector<int>left=judge(root->left);
- vector<int>right=judge(root->right);
-
- int valYes=root->val+left[0]+right[0];//偷当前节点
- int valNo=max(left[0],left[1])+max(right[0],right[1]);
- return {valNo,valYes};
- }
-
-
- };
- class Solution {
- public:
- int maxProfit(vector<int>& prices) {
- //分析:只有卖出>买入才有利润,只能买一次
- int res=0,minNum=INT_MAX;
- for(auto it:prices){
- minNum=min(it,minNum);
- res=max(it-minNum,res);
- }
- return res;
- }
- };
思路二:
1.dp存储:
2.dp
3.初始化:
4.遍历顺序:
- class Solution {
- public:
- int maxProfit(vector<int>& prices) {
- int n=prices.size();
- vector<vector<int>> dp(n,vector
(2)); - dp[0][0]-=prices[0];//持有
- dp[0][1]=0;//不持有
- for(int i=1;i<n;i++){
- dp[i][0]=max(dp[i-1][0],-prices[i]);//当前持有(之前买的和当前买的取最大值)
- dp[i][1]=max(dp[i-1][1],prices[i]+dp[i-1][0]);//当前不持有(之前就不持有和今天不持有)
- }
- return dp[n-1][1];
- }
- };
- class Solution {
- public:
- int maxProfit(vector<int>& prices) {
- int res=0;
- for(int i=1;i
size();i++){ - if(prices[i]>prices[i-1]) res+=prices[i]-prices[i-1];
- }
- return res;
-
- }
- };