[lintcode]150 · 买卖股票的蕞佳时机 II

描述

给定一个数组 prices 表示一支股票每天的价格.

交易次数不限, 不过你不能同时参与多个交易 (也就是说, 如果你已经持有这支股票, 在再次购买之前, 你必须先卖掉它).

设计一个算法求出最大的利润.

样例

样例 1:

 
输入: [2, 1, 2, 0, 1]
输出: 2
解释: 
    1. 在第 2 天以 1 的价格买入, 然后在第 3 天以 2 的价格卖出, 利润 1
    2. 在第 4 天以 0 的价格买入, 然后在第 5 天以 1 的价格卖出, 利润 1
    总利润 2.

样例 2:

 
输入: [4, 3, 2, 1]
输出: 0
解释: 不进行任何交易, 利润为0.

 动态规划解法

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        if(prices.length==0) return 0;
        // write your code here
        int[][] dp = new int[prices.length+1][2];
        for(int i=1;i<prices.length;i++){
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1]+prices[i]-prices[i-1]);
            dp[i][1] = Math.max(dp[i-1][1], dp[i][0]);
        }

        return Math.max(dp[prices.length-1][0], dp[prices.length-1][1]);
    }
}

 贪心解法

刚开始按照正常的思路去想,后来发现可以简化,因为连续的每次买卖与一次卖的效果其实是一样的

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        int buy=-1;
        int res=0;
        for(int i=0;i<prices.length-1;i++){
            if(buy==-1&&prices[i+1]>prices[i]){
                buy = prices[i];
            }
            if(buy!=-1&&prices[i+1]<prices[i]){
                res+=prices[i]-buy;
                buy = -1;
            }
        }
        if(buy!=-1) res+=prices[prices.length-1]-buy;
        return res;
    }
}

简化后

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        int res=0;
        for(int i=0;i<prices.length-1;i++){
            if(prices[i+1]>prices[i]) res+=prices[i+1]-prices[i];
        }
        return res;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值