牛客网:NC134 买卖股票的最好时机(二)

package com.company.test.买卖股票的最好时机2;

/**
 * @author xienl
 * @description 买卖股票的最好时机
 * @date 2022/9/1
 */

public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();

    }

    /**
     * 动态规划
     * @param prices
     * @return
     */
    public int maxProfit (int[] prices) {
        // write code here
        int[][] dp = new int[prices.length][2];
        // 0 代表不持有股票, 1代表持有股票
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int  i = 1; i < prices.length; i++){
            // 当天未持有股票。那么最大收益要么是之前未持有股票的收益。要么就是当天卖出股票的收益
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            // 当天持有股票,结果是钱几天持有的最大值,或者说今天把股票卖出的最大值
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        // 最后一天不持股票的最大价值
        return dp[prices.length - 1][0];
    }

    /**
     * 贪心, 只需要计算当天是否是比前一天便宜,如果便宜就直接卖出
     * @param prices
     * @return
     */
    public int maxProfit2 (int[] prices) {
        // write code here
       int res = 0;
       for (int i = 1; i < prices.length; i++){
           if (prices[i] > prices[ i - 1]){
               res += prices[i] - prices[i - 1];
           }
       }
       return  res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值