function best = find_best_n(v) %v should be a vector of positive integers in nonincreasing order, with %length at least 2. %k will be the value occurring in v that minimizes the sum of all %occurrences of k. In case of a tie, the larger k is used, unless the %smaller k is 1, in which case 1 is used. %The answer is a structure, with fields num, first, last, and total. best.total = sum(v) + 1; l = length(v); i = 1; while i <= l j = i; c = v(i); while j < l && v(j + 1) == c j = j + 1; end t = c*(j - i + 1); if t < best.total || (c == 1 && t == best.total) best.total = t; best.num = c; best.first = i; best.last = j; end i = j + 1; end