如何找到数组中最大的差异

时间:2013-09-23 10:15:17

标签: c# algorithm puzzle

假设我有一个整数数组:

int[] A = { 10, 3, 6, 8, 9, 4, 3 };

我的目标是找到A [Q]和A [P]之间的最大差异,使得Q> P上。

例如,如果P = 2且Q = 3,那么

diff = A[Q] - A[P]
diff = 8 - 6
diff = 2

如果P = 1且Q = 4

diff = A[Q] - A[P]
diff = 9 - 3
diff = 6

由于6是所有差异之间的最大数字,这就是答案。

我的解决方案如下(在C#中),但效率很低。

public int solution(int[] A) {

    int N = A.Length;
    if (N < 1) return 0;

    int difference;
    int largest = 0;

    for (int p = 0; p < N; p++)
    {
        for (int q = p + 1; q < N; q++)
        {
            difference = A[q] - A[p];
            if (difference > largest)
            {
                largest = difference;
            }
        }
    }

    return largest;
}

如何改进,以便在O(N)下运行?谢谢!

简单地让最大和最小不会工作。 Minuend(Q)应该在Subtrahend(P)之后。

这个问题是基于鳕鱼的“最大利润”问题(http://codility.com/train/)。我的解决方案只得到了66%。它要求O(N)得分为100%。

10 个答案:

答案 0 :(得分:19)

以下代码在O(n)中运行,而符合规范(对代码的初步测试成功):

public int solution(int[] A)
{
    int N = A.Length;
    if (N < 1) return 0;

    int max = 0;
    int result = 0;

    for(int i = N-1; i >= 0; --i)
    {
        if(A[i] > max)
            max = A[i];

        var tmpResult = max - A[i];        
        if(tmpResult > result)
            result = tmpResult;
    }

    return result;
}

更新:
我提交了它作为解决方案,它得分为100%。

更新02/26/16:
关于codility的原始任务描述表明“数组A的每个元素都是[0..1,000,000,000]范围内的整数。”
如果也允许负值,则上面的代码不会返回正确的值。通过将max的声明更改为int max = int.MinValue;

,可以轻松解决此问题

答案 1 :(得分:3)

这是O(n)Java实现

public static int largestDifference(int[] data) {
    int minElement=data[0], maxDifference=0;

    for (int i = 1; i < data.length; i++) {
        minElement = Math.min(minElement, data[i]);
        maxDifference = Math.max(maxDifference, data[i] - minElement);
    }
    return maxDifference;
}

答案 2 :(得分:1)

经过一番尝试,我最终得到了这个:

int iMax = N - 1;
int min = int.MaxValue, max = int.MinValue;
for (int i = 0; i < iMax; i++) {
    if (min > A[i]) min = A[i];                                     
    if (max < A[N - i - 1]){
      iMax = N - i - 1;
      max = A[iMax];
    }        
 }
 int largestDiff = max - min;

注意:我刚刚测试了一些情况。如果您发现任何不起作用的情况,请在评论中告诉我。我会尝试改进它或删除答案。谢谢!

答案 3 :(得分:0)

  int FirstIndex = -1;
            int SecondIndex = -1;
            int diff = 0;

            for (int i = A.Length-1; i >=0; i--)
            {
                int FirstNo = A[i];
                int tempDiff = 0;
                for (int j = 0; j <i ; j++)
                {
                    int SecondNo = A[j];
                    tempDiff = FirstNo - SecondNo;
                    if (tempDiff > diff)
                    {
                        diff = tempDiff;
                        FirstIndex = i;
                        SecondIndex = j;
                    }
                }
            }

            MessageBox.Show("Diff: " + diff + "   FirstIndex: " + (FirstIndex+1) + "   SecondIndex: " + (SecondIndex+1));

答案 4 :(得分:0)

PHP解决方案

<?php
$a = [0,5,0,5,0];
$max_diff = -1;
$min_value = $a[0];
for($i = 0;$i<count($a)-1;$i++){
    if($a[$i+1] > $a[$i]){
        $diff = $a[$i+1] - $min_value;
        if($diff > $max_diff){
            $max_diff = $diff;
        }
    } else {
        $min_value = $a[$i+1];
    }
}
echo $max_diff;
?>

答案 5 :(得分:0)

我们可以通过计算数组的最大和最小元素以一种更简单的方式进行操作。我知道您也在寻找时间复杂性。但是对于希望以简单易懂的方式理解和解决此问题的任何人,这是我的代码: enter image description here

#include<stdio.h>  
  
#define N 6  
  
int main()  
{  
    int num[N], i, big, small, pos = 0;  
  
    printf("Enter %d integer numbers\n", N);  
    for(i = 0; i < N; i++)  
        scanf("%d", &num[i]);  
  
    big = small = num[0];  
  
    for(i = 1; i < N; i++)  
    {  
        if(num[i] > big)  
        {  
            big = num[i];  
            pos = i;  
        }  
    }  
  
    for(i = 1; i < pos; i++)  
    {  
        if(num[i] < small)  
            small = num[i];  
    }  
  
    printf("The largest difference is %d, ", (big - small));  
    printf("and its between %d and %d.\n", big, small);  
  
    return 0;  
} 

输出:

输入6个整数

7

9

5

6

13

2

最大差异是8,介于13和5之间。

enter image description here

来源: C Program To Find Largest Difference Between Two Elements of Array

答案 6 :(得分:0)

针对MaxProfit的Codility测试任务的C ++解决方案,给出100/100 https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/

int Max(vector<int> &A)
{
    if (A.size() == 1 || A.size() == 0)
        return 0;
    int min_price = A[0];
    int max_val = 0;
    for (int i = 1; i < A.size(); i++)
    {
        max_val = std::max(max_val, A[i] - min_price);
        min_price = std::min(min_price, A[i]);
    }
    return max_val;
}

答案 7 :(得分:-1)

用于在http://www.rationalplanet.com/php-related/maxprofit-demo-task-at-codility-com.html找到100/100的代码测试任务的MaxProfit的PHP解决方案

function solution($A) {
    $cnt = count($A);
    if($cnt == 1 || $cnt == 0){
        return 0;
    }

    $max_so_far = 0;
    $max_ending_here = 0;
    $min_price = $A[0];

    for($i = 1; $i < $cnt; $i++){
        $max_ending_here = max(0, $A[$i] - $min_price);
        $min_price = min($min_price, $A[$i]);
        $max_so_far = max($max_ending_here, $max_so_far);
    }

    return $max_so_far;
}

答案 8 :(得分:-1)

100%得分JavaScript解决方案。

function solution(A) {
  if (A.length < 2)
    return 0;

  // Init min price and max profit
  var minPrice = A[0];
  var maxProfit = 0;

  for (var i = 1; i < A.length; i++) {
    var profit = A[i] - minPrice;
    maxProfit = Math.max(maxProfit, profit);
    minPrice = Math.min(minPrice, A[i]);
  }
  return maxProfit;
}

答案 9 :(得分:-1)

使用更优雅的功能方法获得100%的Javascript解决方案。

{{1}}