【发布时间】: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 天,依此类推!
-
我已经在下面发布了针对您的情况的完整答案。如果您觉得它有用,请点赞和/或选择它作为正确答案。