找到最大的减少和增加

时间:2020-08-16 20:09:19

标签: c

我想找到最大的减少和增加百分比。我认为我的代码有效,但是我想找到更快速的方法。因为我在2秒内尝试了随机情况下的代码。我的成功率是33%。在其他情况下,由于我设置了2秒的限制,因此发生了超时错误。 (如果没有减少或增加,则结果必须为-1)

void maxmin(double* arr, int n) {
    double max = -1;
    double min = -1;
    for (int i = 0; i < n - 1; i++) {
        for (int j = i+1; j < n; j++) {
            double temp = ((arr[i] - arr[j]) / arr[i]);
            if (temp > 0) {
                if (min == -1)
                    min = temp;
                else if (min < temp)
                    min = temp;
            }
            else {
                if (max == -1)
                    max = temp;
                else if (max > temp)
                    max = temp;
            }
        }
    }

    if (max != -1)
        max = max * (-1);
    
    if (min == -1)
        printf("%.10f\n", min);
    else
        printf("%.10f\n", min*100);
    
    if (max == -1)
        printf("%.10f\n", max);
    else
        printf("%.10f\n", max*100);

}

2 个答案:

答案 0 :(得分:1)

您的算法存在的问题是它需要O(n^2)时间。不过,您可以观察到:处理a[i]时,您只关心先前遇到的a[j]的最小值和最大值。

因此,您可以通过维持到目前为止所见的O(n) s的最大值和最小值来使算法花费a[j]时间。

伪代码:

min_aj := a[0]
max_aj := a[0]
for i = 1, ..., n - 1:
  1. only consider (a[i] - min_aj)/a[i] and (a[i] - max_aj)/a[i]
  2. now, min_aj = min(min_aj, a[i])
  3. and, max_aj = max(max_aj, a[i])

答案 1 :(得分:0)

关于优化索引的荣誉。我建议将您的某些if-else块转换为switch语句,这有助于运行时。有关更多讨论,请参见以下内容:Advantage of switch over if-else statement

此外,可能值得初始化max = -1和min = 10000000(或其他足够大的数字)并直接与该元素进行比较,这可以帮助您避免某些if-else逻辑。

也就是说(就后者而言),选择类似的东西:

double max;
max=-1;
double min;
min=100000;

for (int i = 0; i < n - 1; i++) {
        for (int j = i+1; j < n; j++) {
            temp=((arr[i] - arr[j]) / arr[i]);
            if (temp>max){
                max=temp;
            if (temp < min) {
                min=temp;
            }
        }
    }
}

清理逻辑结构。我将转换留给您切换语句。祝你好运!