Давлен несортированный массив целых чисел с четным количеством элементов,
где сумма всех целых чисел всегда больше, чем ноль, найдите, сколько
элементов (как минимум) следует переместить от начала массива к
его концу, чтобы сумма элементов в первой половине массива не была
отрицательной.
Я не могу найти соответствующую проблему в leetcode или geeksforgeek.
Пожалуйста, помогите мне или поделитесь оптимизированное решение (Java) с программным вводом и выводом
-- Примеры ввода и вывода
Код: Выделить всё
new int[]{3, -1, 2, -2, 5, -3}); // Output: 0
new int[]{1, -2, -3, 4, 5, -1}); // Output: 1
new int[]{10, -5, -5, -5, 20, -10}); // Output: 0
new int[]{-3, -2, 4, 5, 1, 2}); // Output: 1
new int[]{1, 2, 3, -6, 5, 6}); // Output: 1
Код: Выделить всё
private static int minMoves(int[] nums) {
System.out.println("Input nums: " + Arrays.toString(nums));
int n = nums.length;
int k = n / 2; // First half size
int currentSum = 0;
// Calculate the initial sum of the first half
for (int i = 0; i < k; i++) {
currentSum += nums[i];
}
// If the initial sum is non-negative, no moves are needed
if (currentSum >= 0) {
System.out.println("Minimum moves required: " + 0 + " \n");
return 0;
}
// Initialize the minMoves counter
int minMoves = k; // Start with the worst case (move all k elements)
for (int i = 0; i < k; i++) {
// Move nums[i] to the end
currentSum -= nums[i];
// Check if the new sum is non-negative
if (currentSum >= 0) {
minMoves = Math.min(minMoves, i + 1);
}
}
// Return the minimum moves required
System.out.println("Minimum moves required: " + minMoves + " \n");
return minMoves;
}
Заранее спасибо
Подробнее здесь: https://stackoverflow.com/questions/790 ... nd-outputs
Мобильная версия