当前位置:网站首页>JZ63 股票的最大利润
JZ63 股票的最大利润
2022-07-02 09:42:00 【魑魅魍魉114】
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
思路:
我们来假设自己来购买股票。随着时间的推移,每天我们都可以选择出售股票与否。那么,假设在第 i 天,如果我们要在今天卖股票,那么我们能赚多少钱呢?
显然,如果我们真的在买卖股票,我们肯定会想:如果我是在历史最低点买的股票就好了!太好了,在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的。那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice。
因此,我们只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?当考虑完所有天数之时,我们就得到了最好的答案。
实现代码
public int maxProfit(int[] prices) {
int maxProfit = 0;
int minPrice = Integer.MAX_VALUE;
for(int i = 0; i < prices.length;i++){
if(prices[i] < minPrice){
minPrice = prices[i];
}
else if(prices[i] - minPrice > maxProfit){
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
边栏推荐
- Mish-撼动深度学习ReLU激活函数的新继任者
- The position of the first underline selected by the vant tabs component is abnormal
- QT meter custom control
- K-Means Clustering Visualization in R: Step By Step Guide
- GGPlot Examples Best Reference
- Take you ten days to easily finish the finale of go micro services (distributed transactions)
- Industry analysis
- GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
- Deep understanding of NN in pytorch Embedding
- K-Means Clustering Visualization in R: Step By Step Guide
猜你喜欢
Natural language processing series (II) -- building character level language model using RNN
From scratch, develop a web office suite (3): mouse events
jenkins 凭证管理
Deep understanding of NN in pytorch Embedding
A sharp tool for exposing data inconsistencies -- a real-time verification system
Filtre de profondeur de la série svo2
Power Spectral Density Estimates Using FFT---MATLAB
The selected cells in Excel form have the selection effect of cross shading
xss-labs-master靶场环境搭建与1-6关解题思路
FLESH-DECT(MedIA 2021)——一个material decomposition的观点
随机推荐
How to Visualize Missing Data in R using a Heatmap
MySQL stored procedure cursor traversal result set
求16以内正整数的阶乘,也就是n的阶层(0=<n<=16)。输入1111退出。
conda常用命令汇总
Esp32 audio frame esp-adf add key peripheral process code tracking
Deep understanding of NN in pytorch Embedding
【C语言】杨辉三角,自定义三角的行数
Larvel modify table fields
HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
Cluster Analysis in R Simplified and Enhanced
From scratch, develop a web office suite (3): mouse events
Cluster Analysis in R Simplified and Enhanced
B high and beautiful code snippet sharing image generation
How to Add P-Values onto Horizontal GGPLOTS
PHP query distance according to longitude and latitude
Implementation of address book (file version)
进入前六!博云在中国云管理软件市场销量排行持续上升
excel表格中选中单元格出现十字带阴影的选中效果
时间格式化显示
to_ Bytes and from_ Bytes simple example