Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static class Solution {
- public int solution(int[] A) {
- int min1 = Integer.MAX_VALUE;
- int min2 = Integer.MAX_VALUE;
- int minIndex1 = 1;
- int minIndex2 = 1;
- // First min
- for (int i = 1; i < A.length - 1; i++) {
- if (A[i] < min1) {
- min1 = A[i];
- minIndex1 = i;
- }
- }
- // Second min
- for (int i = 1; i < A.length - 1; i++) {
- if (i != minIndex1) {
- if (A[i] < min2) {
- min2 = A[i];
- minIndex2 = i;
- }
- }
- }
- // If they're not adjacent return first and second min
- if (Math.abs(minIndex1 - minIndex2) > 1) {
- return min1 + min2;
- }
- // Find third min
- int min3 = Integer.MAX_VALUE;
- int minIndex3 = 1;
- for (int i = 1; i < A.length - 1; i++) {
- if (i != minIndex1 && i != minIndex2) {
- if (A[i] < min3) {
- min3 = A[i];
- minIndex3 = i;
- }
- }
- }
- if (Math.abs(minIndex1 - minIndex3) > 1) {
- return min1 + min3;
- } else {
- return min2 + min3;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement