输入:
n
(int
) 和n
值 (float
),表示汇率(它们之间不同),随机值介于4
和之间5
。输出:计算可用于(以相同顺序)表示先升后降曲线的值的最大数量?
ex 八个值
4.5 4.6 4.3 4.0 4.8 4.4 4.7 4.1
应该输出
5 (4.5 4.6 4.8 4.4 4.1)
我的方法
- 如果我尝试连续
if
的 s,我会得到一个尊重曲线条件的随机数组,但不是最长的。 - 我没有尝试回溯,因为我对它不是很熟悉,但有些事情告诉我,我必须用它计算所有解决方案,然后选择最长的。
- 最后:蛮力,但因为它是算法设计的任务;我还不如不交。:)
有没有更简单/更有效/更快的方法?
这是我基于 Daniel Lemire 算法的尝试。似乎它没有考虑位置 0、i 和 n。我确定ifs是问题所在,我该如何解决它们?
for(int i = 0; i<n-1; i++){
int countp=0; // count ascending
int countn=0; // count descending
for(int j=0;j<=i;j++){
if(currency[j]<currency[j+1]){
countp++;
System.out.print(j+" ");
}
}
System.out.print("|| ");
for(int j=i;j<n-1;j++){
if(currency[j]>currency[j+1]){
countn++;
System.out.print(j+" ");
}
}
System.out.println();
if(countn+countp>maxcount) maxcount=countn+countp;
}