|
| 1 | +#include <algorithm> |
| 2 | +#include <vector> |
| 3 | +#include <queue> |
| 4 | +#include <set> |
| 5 | +#include <limits> |
| 6 | +#include <map> |
| 7 | +#include <unordered_set> |
| 8 | +#include <unordered_map> |
| 9 | +#include <iterator> |
| 10 | +#include <sstream> |
| 11 | +#include <iostream> // includes cin to read from stdin and cout to write to stdout |
| 12 | +using namespace std; // since cin and cout are both in namespace std, this saves some text |
| 13 | + |
| 14 | +class Solution { |
| 15 | +public: |
| 16 | + int maxDistance(vector<vector<int>>& arrays) { |
| 17 | + int smallest = numeric_limits<int>::max(); |
| 18 | + int secondSmallest = numeric_limits<int>::max(); |
| 19 | + int largest = numeric_limits<int>::min(); |
| 20 | + int secondLargest = numeric_limits<int>::min(); |
| 21 | + |
| 22 | + for (auto &array: arrays) { |
| 23 | + if (array.size() == 0) { |
| 24 | + continue; |
| 25 | + } |
| 26 | + |
| 27 | + auto first = *begin(array); |
| 28 | + if (first <= smallest) { |
| 29 | + secondSmallest = smallest; |
| 30 | + smallest = first; |
| 31 | + } else if (first <= secondSmallest) { |
| 32 | + secondSmallest = first; |
| 33 | + } |
| 34 | + |
| 35 | + auto last = *prev(end(array)); |
| 36 | + if (last >= largest) { |
| 37 | + secondLargest = largest; |
| 38 | + largest = last; |
| 39 | + } else if (last >= secondLargest) { |
| 40 | + secondLargest = last; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + int answer = 0; |
| 45 | + for (auto &array: arrays) { |
| 46 | + if (array.size() == 0) { |
| 47 | + continue; |
| 48 | + } |
| 49 | + |
| 50 | + auto first = *begin(array); |
| 51 | + auto last = *prev(end(array)); |
| 52 | + if (first == smallest && last == largest) { |
| 53 | + answer = max(answer, max(last - secondSmallest, secondLargest - first)); |
| 54 | + // } else if (first == smallest) { |
| 55 | + // answer = max(answer, max(last - secondSmallest, secondLargest - first)); |
| 56 | + // } else if (last == largest) { |
| 57 | + } else { |
| 58 | + answer = max(answer, max(last - smallest, largest - first)); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return answer; |
| 63 | + } |
| 64 | +}; |
0 commit comments