java 盈利_java 动态规划判断股票最大盈利问题

题目:web

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.

解题思路:数组

这道题很是直观也很是简单。想要经过一次买卖获得的利润,就是要找到一组 i 和 j ,使得 prices[j] - prices[i] 最大,而且知足 i < j 。由于第二个约束条件,咱们不会傻到找一个最大值和最小值而且返回它们的差。svg

假设 f[i] 为到第 i 天为止能够拿到的最大利润。对于第 i 天,有两种选择,即在当天卖掉股票,或者在第 i 天以前已经卖掉了。那么 f[i] 就是这两种选择中的最大值。若是在第 i 天卖掉股票,那么问题就是在哪天买股票,只要维护一个到第 i 天为止股价的最小值 minPrice 就能够了,此时 f[i] = prices[i] - minPrice ;若是在第 i 天股票已经卖出,则 f[i] = f[i-1] 。优化

综上所述,令 f[i] 表示到第 i 天为止能够拿到的最大利润。状态转移方程为 f[i] = max(f[i-1], prices[i] - minPrice) ,其中 minPrice 表示到第 i 天为止的最低股价,而且有 minPrice = min(minPrice, prices[i]) 。边界条件为 f[0] = 0, minPrice = prices[0] 。最终结果为 f[n-1] 。时间复杂度与空间复杂度均为 O(n) 。ui

观察状态方程能够发现, f[i] 的值只与 f 数组中的 f[i-1] 有关。也就是说,在计算 f[i] 时,只要保留 f[i-1] 的值就行了,其余的值均可以不保存。据此能够优化空间复杂度。spa

令 profit 表示到第 i 天为止能够拿到的最大利润。状态转移方程为 profit = max(profit, prices[i] - minPrice) 。 profit 初始化为 0 。最终结果即保存在 profit 中。时间复杂度为 O(n) ,空间复杂度为 O(1) 。 code

解法以下:server

public class Solution {

public int maxProfit(int[] prices) {

if(prices==null||prices.length==0){

return 0;

}

int max = 0;

int[] f = new int[prices.length];

int minPrice = prices[0];

f[0] = 0;

for(int i=1;i

f[i] = max(f[i-1],prices[i]-minPrice);

minPrice = min(minPrice,prices[i]);

if(f[i]>max)

max = f[i];

}

return max;

}

public int max(int a,int b){

return a>b?a:b;

}

public int min(int a,int b){

return a

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值