leetcode算法笔记-买卖股票的最佳时机 II

学习目标:

买卖股票的最佳时机 II

学习内容:

动态规划
贪心算法

贪心:

①建立数学模型来描述问题 。
②把求解的问题分成若干个子问题
③对每个子问题求解,得到子问题的局部最优解
④把子问题的局部最优解合成原来解问题的一个解 。

贪心算法也存在如下问题:
1、不能保证解是最佳的。因为贪心算法总是从局部出发,并没从整体考虑
2、贪心算法一般用来解决求最大或最小解
3、贪心算法只能确定某些问题的可行性范围 。
C++


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

python

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1, len(prices)):
            tmp = prices[i] - prices[i - 1]
            if tmp > 0: profit += tmp
        return profit

动态规划:

多阶段决策问题中,各个阶段采取的决策,一般来说是与时间有关的,决策依赖于当前状态,又随即引起状态的转移,一个决策序列就是在变化的状态中产生出来的,故有“动态”的含义,称这种解决多阶段决策最优化问题的方法为动态规划方法 。
1、建立状态变化(转移)方程
2、对之前状态进行复用
3、从前到后的进行递归出结果
C++

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int dp[n][2]; //所有天数的交易状态 0为无股票 1 为持有 可优化为当天和前一天
        dp[0][0] = 0, dp[0][1] = -prices[0];
        for (int i = 1; i < n; ++i) {
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        return dp[n - 1][0];
    }
};

python

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        dp0 = 0             # 手里没股票
        dp1 = - prices[0]   # 手里有股票
        for i in range(1, len(prices)):
            dp0 = max(dp0, dp1 + prices[i])
            dp1 = max(dp1, dp0 - prices[i])
        return dp0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值