当前位置:网站首页>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;
}边栏推荐
- YYGH-BUG-05
- H5,为页面添加遮罩层,实现类似于点击右上角在浏览器中打开
- Three transparent LED displays that were "crowded" in 2022
- [visual studio 2019] create MFC desktop program (install MFC development components | create MFC application | edit MFC application window | add click event for button | Modify button text | open appl
- HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
- Mish-撼动深度学习ReLU激活函数的新继任者
- Industry analysis
- PyTorch nn.RNN 参数全解析
- SVO2系列之深度濾波DepthFilter
- uniapp uni-list-item @click,uniapp uni-list-item带参数跳转
猜你喜欢

xss-labs-master靶场环境搭建与1-6关解题思路

小程序链接生成

Develop scalable contracts based on hardhat and openzeppelin (I)

HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R

Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer

SVO2系列之深度滤波DepthFilter

H5,为页面添加遮罩层,实现类似于点击右上角在浏览器中打开

How does Premiere (PR) import the preset mogrt template?

SVO2系列之深度濾波DepthFilter

Power Spectral Density Estimates Using FFT---MATLAB
随机推荐
6. Introduce you to LED soft film screen. LED soft film screen size | price | installation | application
多文件程序X32dbg动态调试
Cluster Analysis in R Simplified and Enhanced
HOW TO ADD P-VALUES ONTO A GROUPED GGPLOT USING THE GGPUBR R PACKAGE
动态内存(进阶四)
基于Arduino和ESP8266的Blink代码运行成功(包含错误分析)
数据分析 - matplotlib示例代码
Bedtools tutorial
Research on and off the Oracle chain
On data preprocessing in sklearn
How to Add P-Values onto Horizontal GGPLOTS
浅谈sklearn中的数据预处理
PyTorch搭建LSTM实现服装分类(FashionMNIST)
How does Premiere (PR) import the preset mogrt template?
Summary of flutter problems
GGPlot Examples Best Reference
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
Three transparent LED displays that were "crowded" in 2022
[untitled] how to mount a hard disk in armbian
php 二维、多维 数组打乱顺序,PHP_php打乱数组二维数组多维数组的简单实例,php中的shuffle函数只能打乱一维