DEV Community

Arpit Rathore
Arpit Rathore

Posted on

3264. Final Array State After K Multiplication Operations I

Important links

Intuition

  1. This is simple simulation problem.
  2. Write a method getMin() to find minimum value along with its index from the array (Create a record Pair to return 2 values).
  3. The idea is to iterate the array for k times.
  4. In each iteration, find the minimum value in the array along with its index using getMin().
  5. 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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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]  
Enter fullscreen mode Exit fullscreen mode

Top comments (0)