Important links
- Problem: 3264. Final Array State After K Multiplication Operations I
- Link to parent page: Simulation
- Java Cheat Sheet: link
Intuition
- This is simple simulation problem.
- Write a method
getMin()
to find minimum value along with its index from the array (Create a recordPair
to return 2 values). - The idea is to iterate the array for k times.
- In each iteration, find the minimum value in the array along with its index using
getMin()
. - Update this value in the array using the index by setting nums[i] = minValue * multiplier
Solution
class Solution {
record Pair(int value, int index) {}
public int[] getFinalState(int[] nums, int k, int multiplier) {
for (int i = 0; i < k; i++) {
Pair minPair = getMin(nums);
nums[minPair.index] = minPair.value * multiplier;
System.out.printf("Min %s. nums after replacement: %s %n", minPair, Arrays.toString(nums));
}
return nums;
}
private Pair getMin(int[] nums) {
Pair minPair = new Pair(Integer.MAX_VALUE, -1);
for (int i = 0; i < nums.length; i++) {
if (nums[i] < minPair.value) {
minPair = new Pair(nums[i], i);
}
}
return minPair;
}
}
Visualisation
I have added print statement to visualise the minValue
and nums
in each iteration:
Input: nums=[2,1,3,5,6], k=5, multiplier=2
Std out:
Min Pair[value=1, index=1]. nums after replacement: [2, 2, 3, 5, 6]
Min Pair[value=2, index=0]. nums after replacement: [4, 2, 3, 5, 6]
Min Pair[value=2, index=1]. nums after replacement: [4, 4, 3, 5, 6]
Min Pair[value=3, index=2]. nums after replacement: [4, 4, 6, 5, 6]
Min Pair[value=4, index=0]. nums after replacement: [8, 4, 6, 5, 6]
Top comments (0)