JAVA:实现买入和卖出股票的最佳时机算法(附完整源码)

JAVA:实现买入和卖出股票的最佳时机算法


public class BestTimeToBuyAndSellStock {
   
    public int maxProfit(int[] prices) {
   
        //Kadane's algorithm
        if(prices.length == 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是Java实现Romberg算法完整源码: ```java import java.util.Scanner; public class RombergAlgorithm { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the lower limit of integration: "); double a = sc.nextDouble(); System.out.print("Enter the upper limit of integration: "); double b = sc.nextDouble(); System.out.print("Enter the number of sub-intervals: "); int n = sc.nextInt(); double[][] R = new double[n + 1][n + 1]; // Compute R[0][0] double h = b - a; R[0][0] = (h / 2) * (f(a) + f(b)); // Compute R[i][0] for i = 1, 2, ..., n for (int i = 1; i <= n; i++) { h /= 2; double sum = 0; for (int j = 1; j <= Math.pow(2, i - 1); j++) { sum += f(a + (2 * j - 1) * h); } R[i][0] = 0.5 * R[i - 1][0] + sum * h; } // Compute R[i][j] for i = j, j + 1, ..., n for (int j = 1; j <= n; j++) { for (int i = j; i <= n; i++) { R[i][j] = (Math.pow(4, j) * R[i][j - 1] - R[i - 1][j - 1]) / (Math.pow(4, j) - 1); } } // Print R table System.out.println("\nR Table:"); for (int i = 0; i <= n; i++) { for (int j = 0; j <= i; j++) { System.out.printf("%.6f\t", R[i][j]); } System.out.println(); } // Print result System.out.printf("\nIntegral value: %.6f", R[n][n]); } // Define the function to be integrated public static double f(double x) { return Math.sin(x) / x; } } ``` 代码中使用了一个二维数组R来存储Romberg表格中的数值,其中R[i][j]表示用2^j个子区间计算第i次迭代的积分估计值。 程序首先读取积分区间和子区间个数,并计算出R[0][0]的值。然后,使用递推公式计算R[i][0](其中i为1到n),再利用递推公式计算R[i][j](其中i为j到n,j为1到n)。 最后,程序输出Romberg表格和最终积分估计值。 以上是Java实现Romberg算法完整源码,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源代码大师

赏点狗粮吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值