Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. static class Solution {
  2.         public int solution(int[] A) {
  3.  
  4.             int min1 = Integer.MAX_VALUE;
  5.             int min2 = Integer.MAX_VALUE;
  6.             int minIndex1 = 1;
  7.             int minIndex2 = 1;
  8.  
  9.             // First min
  10.             for (int i = 1; i < A.length - 1; i++) {
  11.                 if (A[i] < min1) {
  12.                     min1 = A[i];
  13.                     minIndex1 = i;
  14.                 }
  15.             }
  16.  
  17.             // Second min
  18.             for (int i = 1; i < A.length - 1; i++) {
  19.                 if (i != minIndex1) {
  20.                     if (A[i] < min2) {
  21.                         min2 = A[i];
  22.                         minIndex2 = i;
  23.                     }
  24.                 }
  25.             }
  26.  
  27.             // If they're not adjacent return first and second min
  28.             if (Math.abs(minIndex1 - minIndex2) > 1) {
  29.                 return min1 + min2;
  30.             }
  31.  
  32.             // Find third min
  33.             int min3 = Integer.MAX_VALUE;
  34.             int minIndex3 = 1;
  35.  
  36.             for (int i = 1; i < A.length - 1; i++) {
  37.                 if (i != minIndex1 && i != minIndex2) {
  38.                     if (A[i] < min3) {
  39.                         min3 = A[i];
  40.                         minIndex3 = i;
  41.                     }
  42.                 }
  43.             }
  44.  
  45.             if (Math.abs(minIndex1 - minIndex3) > 1) {
  46.                 return min1 + min3;
  47.             } else {
  48.                 return min2 + min3;
  49.             }
  50.         }
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement