最大单一销售利润算法(Java)

时间:2016-04-09 01:40:43

标签: java algorithm recursion

我正在创建一个算法,以便从.txt文件中获得最大利润,其中每一行是一天中某个股票的价格(从第0天开始)。

我的程序输出应该是“[你应该买股票的那一天,你应该卖出股票的那一天,赚取的利润]”。

例如:

文字档案: 12,45,3,15,60,23,4

输出应为[2,4,57]。

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

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

我是初学者,我似乎无法找到如何做出正确的输出!非常感谢帮助!

(交易是一个单独的类,返回(in,out,profit))。

[编辑]:我应该递归地执行此操作,并确保解决方案的总时间成本为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;
    }
}

3 个答案:

答案 0 :(得分:0)

获得数组后,您只需运行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));

答案 1 :(得分:0)

检查 -

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]

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

答案 2 :(得分:0)

myRecord.subscribe(data => {})