【问题标题】:Maximum Single Sell Profit algorithm (Java)最大单笔销售利润算法 (Java)
【发布时间】:2016-04-09 01:40:43
【问题描述】:

我正在创建一种算法,以最大限度地提高 .txt 文件的利润,其中每一行是某只股票在一天(从第 0 天开始)的价格。

我的程序的输出应该是“[你应该买股票的日子,你应该卖股票的日子,获利]”。

例如:

文本文件: 12、45、3、15、60、23、4

输出应该是 [2, 4, 57]。

我的代码返回实际值,而不是这些值的索引。

我的输出:[3, 60, 57]。

我是初学者,我似乎不知道如何才能产生正确的输出!非常感谢您的帮助!

(Trade 是一个单独的类,它返回(进、出、利润))。

[编辑]:我应该递归地执行此操作,并确保解决方案的总时间成本为 O(n log n)!

这是我的代码: (如果杂乱无章/里面有不需要的东西,请道歉!:))

import java.util.*;
import java.lang.Math;
import java.io.*;

public class Test_BestTrading
{
   public static void main(String[] args) throws Exception
   {
      //open file
      String fileName = args[0];
      File inFile = new File(fileName);
      Scanner fin = new Scanner(inFile);
      int count = 0;

      //find out length of array
      while(fin.hasNext())
      {
         fin.nextLine();
         count++;
      }
      fin.close();

      int[]p = new int[count];
      fin = new Scanner(inFile);

      //read numbers into array
      for(int i =0; i < count; i++)
         p[i] = Integer.parseInt(fin.nextLine());

      Trade trade = BestTrade(p, 0, p.length-1);

      System.out.println("[" + trade.in + ", " + trade.out + ", " + trade.profit + "]");
   }

   public static Trade BestTrade(int[] p, int in, int out)
   {
      if (p.length <= 1)
         return new Trade(in, out, out-in);

      //Create two arrays - one is left half of "p", one is right half of "p".
      int[] left = Arrays.copyOfRange(p, 0, p.length/2);
      int[] right = Arrays.copyOfRange(p, p.length/2, p.length);

      // Find best values for buying and selling only in left array or only in right array
      Trade best_left  = BestTrade(left, 0, left.length-1);
      Trade best_right = BestTrade(right, 0, right.length-1);

      // Compute the best profit for buying in the left and selling in the right.
      Trade best_both = new Trade(min(left), max(right), max(right) - min(left));

      if (best_left.profit > best_right.profit && best_left.profit > best_both.profit)
         return best_left;
      else if (best_right.profit > best_left.profit && best_right.profit > best_both.profit)
         return best_right;
      else
        return best_both;

    }

    public static int max(int[] A)
    {
      int max = 0;

      for(int i=0; i < A.length; i++)
      {
         if(A[i] > max)
            max = A[i];
      }

      return max;
    }

    public static int min(int[] A)
    {
      int min = 100000;

      for(int i=0; i < A.length; i++)
      {
         if(A[i] < min)
            min = A[i];
      }

      return min;
    }
}

【问题讨论】:

  • "输出应该是 [2, 4, 57]。" 如果你这样做,你会不会在第 2 天买入股票(45 美元)然后卖出第 4 天的股票(15 美元)。这似乎不是利润最大化。从外观上看,您的程序运行良好。以 3 美元买入,以 60 美元卖出,获得 57 美元的利润。您只需要提取日期编号而不是前两个的值。
  • 抱歉,我不知道我的问题是否清楚,但它从“第 0 天”开始——所以第 0 天是第 12 天,第 1 天是第 45 天,依此类推!
  • 我已经在下面发布了针对您的情况的完整答案。如果您觉得它有用,请点赞和/或选择它作为正确答案。

标签: java algorithm recursion


【解决方案1】:

获得数字数组后,您可以简单地运行for 循环来检测最小值和最大值以及每个数字的索引。

int greatestDifference = 0;
int indexLowest = 0;
int indexHighest = 0;

for(int i = 0; i < values.length; i++)
    for(int j = i + 1; j < values.length; j++)
        if(values[i] - values[j] < greatestDifference){
            greatestDifference = values[i] - values[j];
            indexLowest = i;
            indexHighest = j;
        }

System.out.println("Buy value is " + values[indexLowest] + " on day " + (indexLowest + 1) + ".");
System.out.println("Sell value is " + values[indexHighest] + " on day " + (indexHighest + 1) + ".");
System.out.println("Net gain is " + Math.abs(greatestDifference));

【讨论】:

  • 此解决方案允许在购买股票之前将其出售。这在现实世界中可能是可能的,但我想这不是问题的意图。例如 [5, 4, 3, 2, 1, 2] 应该给出 [4, 5, 1] 而不是 [4, 0, 4]。
  • @PaulHankin 我很抱歉。我发布了效率较低但有效的代码。
【解决方案2】:

检查一下 -

public class BuySellProfit {

public static void main(String[] args) {

    int[] a = { 12, 45, 3, 15, 60, 23, 4 };
    int min = a[0];
    int max = a[0];
    int minIndex=0;
    int maxIndex=0;
    for (int count = 0; count < a.length; count++) {
        if (a[count] > max) {
            max = a[count];
            maxIndex=count;
        }

    }
    System.out.println("Max = " + max);

    for (int count = 0; count < a.length; count++) {

        if (a[count] < min) {
            min = a[count];
            minIndex=count;
        }
    }
    System.out.println("min=" + min);

    profit(a, minIndex, maxIndex);
}

private static void profit(int a[], int i, int j) {
    int profit = a[j] - a[i];
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(i);
    list.add(j);
    list.add(profit);
    System.out.println(list);
}

}

输出:-

Max = 60
min=3
[2, 4, 57]

您只需返回索引号而不是值, 它会工作..顺便说一句,你的代码没问题。

【讨论】:

    【解决方案3】:
    import java.util.Scanner;
    
    
    public class Example4 {
    
        public static void main(String[] args) {
            //System.out.println("input the valuer:");
            Scanner x =new Scanner(System.in);
            for( int i=1;i<13;i++){
                System.out.println("Profit for month" +i);
                System.out.println("input the valuer :");
                float valuer1 =x.nextFloat();
                float result=0;
    
                result+=valuer1;
                System.out.println("Total profits for  months:"+result);
    
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-28
      • 1970-01-01
      • 2011-11-17
      • 2016-10-14
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 2021-11-20
      相关资源
      最近更新 更多