栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基于java计算买卖股票的最佳时机

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于java计算买卖股票的最佳时机

这篇文章主要介绍了基于java计算买卖股票的最佳时机,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

问题:

可以将问题转化为如下图所示,即求多个累计的收入差

分析:

如果当前位置i的价格比i+1的价格高,则当前不是买入点,则继续判断下一个位置,

如果当前位置i的价格比i+1的价格低,并且i+1仍比i+1+1低,则在当前位置买入,知道i+n比i+n+1大时,卖出。

继续下一轮判断

package com.example.demo;

public class Test121 {

  
  public int maxProfit(int[] prices) {
    if (prices == null || prices.length == 0) {
      return 0;
    }
    int cur = 0;
    int vally = prices[0];
    int peak = 0;
    int income = 0;
    while (cur < prices.length - 1) {
      //找到卖出点,谷底
      while (cur < prices.length - 1 && prices[cur] >= prices[cur + 1]) {
 cur++;
      }
      vally = prices[cur];
      //找到比当前大的值(即最高点,顶峰)
      while (cur < prices.length - 1 && prices[cur] <= prices[cur + 1]) {
 cur++;
      }
      peak = prices[cur];
      income += peak - vally;
      //如果此时cur仍然没有到最后,则进行再一次循环
    }
    return income;
  }

  public static void main(String[] args) {
    Test121 t = new Test121();
    int[] arr = {7, 1, 5, 3, 6, 4};
    int i = t.maxProfit(arr);
    System.out.println(i);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/136695.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号