A Pair with the Maximal Difference

A Pair with the Maximal Difference


Problem: A pair contains two numbers, and its second number is on the right side of the first one in an array. The difference of a pair is the minus result while subtracting the second number from the first one. Please implement a function which gets the maximal difference of all pairs in an array. For example, the maximal difference in the array {2, 4, 1, 16, 7, 5, 11, 9} is 11, which is the minus result of pair (16, 5).




从右往左扫描数组,总是和最小的元素计算diff


#include <stdio.h>

int max_diff(int data[], int n)
{
        int min;
        int diff, m_diff;
        int i = n - 1;

        diff = data[i-1] - data[i];
        m_diff = diff;

        min = data[i];
        if (data[i-1] < min)
                min = data[i-1];
        i = i - 2;
        while (i >= 0) {
                diff = data[i] - min;
                if (diff > m_diff)
                        m_diff = diff;
                if (data[i] < min)
                        min = data[i];
                i--;
        }

        return m_diff;
}

int main()
{
        int data[] = {2, 4, 1, 16, 7, 5, 11, 9};
        int n = 8;

        printf("%d\n", max_diff(data, n));

        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值