Big Difference

/***
There is an integer array consisting positive and negative integers. Find maximum
positive difference S defined as:

S = a[i] - a[j] where i>j
and
S > 0
***/

#include<iostream>

using namespace std;

int bigDiff(int *a, int sz) {
       int min = 0;
       int dif = 0;
       for(int i = 0; i<sz; i++) {
              if (a[i] < 0)
              {
                     if (min > a[i]) min = a[i];
              } else {
                     if (dif < a[i] - min) dif = a[i] - min;
              }
       }
       return dif;
}

void main() {

       int a[] = {-3, -2, 11, -5, 3, 6, 8};
       int sz = sizeof(a) / sizeof(int);
       int diff = bigDiff(a, sz);
       cout<<diff<<endl;

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs