Java Tape Equilibrium
public class Solution {
public static int tapeEquilibrium(int[] a) {
long firstPart = 0;
long secondPart = 0;
for (int v : a) {
secondPart += v;
}
long min = Long.MAX_VALUE;
for (int i = 0; i < a.length - 1; i++) {
firstPart += i;
secondPart -= i;
long difference = Math.abs(firstPart - secondPart);
min = Math.min(min, difference);
}
return (int) min;
}
}
This keeps left and right running sums and updates the smallest difference at each split point.
Java Triangle
import java.util.Arrays;
public class Solution {
public static int triangle(int[] a) {
int[] sorted = a.clone();
Arrays.sort(sorted);
int c = sorted.length;
if (c < 3) {
return 0;
}
for (int i = 0; i < c - 2; i++) {
if (sorted[i] > 0 && sorted[i] > (long) sorted[i + 2] - sorted[i + 1]) {
return 1;
}
}
return 0;
}
}
This sorts the values and checks nearby triples, because a valid triangle only needs one local match after sorting.