博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]: 121: Best Time to Buy and Sell Stock
阅读量:6966 次
发布时间:2019-06-27

本文共 1031 字,大约阅读时间需要 3 分钟。

题目:

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.

 

分析:一维的动态规划(硬算就行吧)

设dp[i]是[0,1,2...i]区间的最大利润,则该问题的一维动态规划方程如下

dp[i+1] = max{dp[i], prices[i+1] - minprices}  ,minprices是区间[0,1,2...,i]内的最低价格

我们要求解的最大利润 = max{dp[0], dp[1], dp[2], ..., dp[n-1]} 

其实关键就是一个是维护最大的利润的记录,一个是维护最大,最小值的记录。且最大值和最小值的其中一个需要和最大利润联动

 

代码:

public int maxProfit(int[] prices) {        if(prices == null || prices.length == 0){            return 0;        }        int Profit = 0;        int Min = prices[0];        int Max = prices[0];                for(int i =1 ;i
Profit){ Max = prices[i]; Profit = Max - Min; }else if(prices[i] - Min < Profit && prices[i] < Min){ Min = prices[i]; } } return Profit; }

 

转载于:https://www.cnblogs.com/savageclc26/p/4871251.html

你可能感兴趣的文章
JAVA分布式架构
查看>>
如何把使用到android res文件夹下面资源(R.xx.xx)的工程打包成jar文件,供其它项目使用...
查看>>
删除Referencing outlet
查看>>
三、hbase JavaAPI
查看>>
Maximum Subarray
查看>>
Android ProGuard使用要点
查看>>
导入自定义模块model
查看>>
Python之初识函数(Day11)
查看>>
[LeetCode] NO.383 Ransom Note
查看>>
App数据分析的五大维度!
查看>>
Authentication and Authorization in ASP.NET Web API
查看>>
nginx
查看>>
MyBatis框架使用(一)
查看>>
Scala学习(八)练习
查看>>
集合内的简单排序
查看>>
设计模式(享元模式)
查看>>
oracle中怎么查看存储过程的源码
查看>>
Django-restframework 之 Exceptions分析
查看>>
下拉弹窗 pop push动画实现
查看>>
top命令查看内容详解
查看>>