Best Time to Buy and Sell Stock(JAVA)--动态规划

题目:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

翻译:
给一个数组,该数组表示股票每天的价格
设计一个计算最大收益的算法,前提是你只能买进一次和卖出一次。

例如:用数组prices={3,2, 5, 1 , 3}表示股票的价格,则最大收益为:3

思路:用数组profit记录从开始到第i天的最大收益,初值为0
minPrice 为最低价格,初始值为第一天的价格
对 prices 数组从第二天开始进行循环:1)如果某天的价格比最小价格小,则该天的最大收益一定和前一天相同,最小价格替换为该天的价格;2)如果某天的价格大于等于最小价格,则取max{将当天的价格减去最小价格,前一天的收益}作为当天的最大收益。

代码(java版)

public class Solution {
    public static int maxProfit(int[] prices) {
        int n = prices.length;
        if(n<2) return 0;
        int minPrice = prices[0];
        int[] profit = new int[n];  //记录从开始到第i天的最大收益
        for(int i = 1; i<n; i++){
            if(prices[i] < minPrice){
                minPrice = prices[i];
                profit[i] = profit[i-1];
            }else{
                int temp = prices[i] - minPrice;
                profit[i] = profit[i-1] > temp ? profit[i-1]:temp;
            }
        }
        return profit[n-1];
    }
}

为降低空间复杂度,可将代码改进如下(在leetcoad上提交后,耗时比前一种方法多,但个人认为这种改进不会增加时间复杂度,可能是提交时间不同,所以显示的的时间不同?):

public class Solution {
    public static int maxProfit(int[] prices) {
        int n = prices.length;
        if(n<2) return 0;
        int minPrice = prices[0];
        int maxProfit = 0;
        for(int i = 1; i<n; i++){
            if(prices[i] < minPrice){
                minPrice = prices[i];
            }else{
                int temp = prices[i] - minPrice;
                maxProfit = maxProfit > temp ? maxProfit:temp;
            }
        }
        return maxProfit;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值