当前位置:网站首页>漫画:寻找股票买入卖出的最佳时机
漫画:寻找股票买入卖出的最佳时机
2022-07-05 16:49:00 【小灰】
————— 第二天 —————
什么意思呢?让我们来举个例子,给定如下数组:
该数组对应的股票涨跌曲线如下:
显然,从第2天价格为1的时候买入,从第5天价格为8的时候卖出,可以获得最大收益:
此时的最大收益是 8-1=7。
在上面这个例子中,最大值9在最小值1的前面,我们又该怎么交易?总不能让时间倒流吧?
————————————
以下图为例,假如我们已经确定价格4的时候为卖出时间点,那么此时最佳的买入时间点是哪一个呢?
我们要选择价格4之前的区间,且必须是区间内最小值,显然,这个最佳的选择是价格2的时间点。
第1步,初始化操作,把数组的第1个元素当做临时的最小价格;最大收益的初始值是0:
第2步,遍历到第2个元素,由于2<9,所以当前的最小价格变成了2;此时没有必要计算差值的必要(因为前面的元素比它大),当前的最大收益仍然是0:
第3步,遍历到第3个元素,由于7>2,所以当前的最小价格仍然是2;如我们刚才所讲,假设价格7为卖出点,对应的最佳买入点是价格2,两者差值7-2=5,5>0,所以当前的最大收益变成了5:
第4步,遍历到第4个元素,由于4>2,所以当前的最小价格仍然是2;4-2=2,2<5,所以当前的最大收益仍然是5:
第5步,遍历到第5个元素,由于3>2,所以当前的最小价格仍然是2;3-2=1,1<5,所以当前的最大收益仍然是5:
以此类推,我们一直遍历到数组末尾,此时的最小价格是1;最大收益是8-1=7:
public class StockProfit {
public static int maxProfitFor1Time(int prices[]) {
if(prices==null || prices.length==0) {
return 0;
}
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else if(prices[i] - minPrice > maxProfit){
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
public static void main(String[] args) {
int[] prices = {9,2,7,4,3,1,8,4};
System.out.println(maxProfitFor1Time(prices));
}
}题目要求每次买入前,必须卖出持有的股票。我们以下图这个数组为例,直观地看一下买入卖出的时机:
在图中,绿色的线段代表价格上涨的阶段。既然买卖次数不限,那么我们完全可以在每一次低点都进行买入,在每一次高点都进行卖出。
这样一来,所有绿色的部分都是我们的收益,最大总收益就是这些局部收益的加总:
(6-1)+(8-3)+(4-2)+(7-4) = 15
至于如何判断出这些绿色上涨阶段呢?很简单,我们遍历整个数组,但凡后一个元素大于前一个元素,就代表股价处于上涨阶段。
public int maxProfitForAnyTime(int[] prices) {
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i-1])
maxProfit += prices[i] - prices[i-1];
}
return maxProfit;
}—————END—————
边栏推荐
猜你喜欢

Machine learning 01: Introduction

阈值同态加密在隐私计算中的应用:解读

Embedded-c Language-1

Judge whether a string is a full letter sentence

Winedt common shortcut key modify shortcut key latex compile button
MYSQL group by 有哪些注意事项
![[Jianzhi offer] 63 Maximum profit of stock](/img/b6/c1dec97a23ac13aa53d1d202b83ef5.png)
[Jianzhi offer] 63 Maximum profit of stock

Machine learning 02: model evaluation

The second day of learning C language for Asian people

机器学习02:模型评估
随机推荐
[binary tree] insufficient nodes on the root to leaf path
Debug kernel code through proc interface
thinkphp3.2.3
拷贝方式之DMA
机器学习02:模型评估
Summary of optimization scheme for implementing delay queue based on redis
Browser rendering principle and rearrangement and redrawing
激动人心!2022开放原子全球开源峰会报名火热开启!
华为云云原生容器综合竞争力,中国第一!
Machine learning 01: Introduction
Rider 设置选中单词侧边高亮,去除警告建议高亮
Embedded UC (UNIX System Advanced Programming) -1
[Jianzhi offer] 61 Shunzi in playing cards
[Jianzhi offer] 66 Build product array
一个满分的项目文档是如何书写的|得物技术
云安全日报220705:红帽PHP解释器发现执行任意代码漏洞,需要尽快升级
ternary operator
7. Scala class
[7.7 live broadcast preview] the lecturer of "typical architecture of SaaS cloud native applications" teaches you to easily build cloud native SaaS applications. Once the problem is solved, Huawei's s
Matery主题自定义(一)黑夜模式