The Indian Engineer

Problem 3264 Final Array State After K Multiplication Operations I

Posted on Last edited 3 mins

Priority-Queue Min-Heap Math

Problem Statement

Link - Problem 3264

Question

You are given an integer array nums, an integer k, and an integer multiplier.

You need to perform k operations on nums. In each operation:

Return an integer array denoting the final state of nums after performing all k operations.

Example 1

Input: nums = [1,2], k = 3, multiplier = 4

Output: [16,8]

Explanation:

| Operation         | Result  |
| ----------------- | ------- |
| After operation 1 | [4, 2]  |
| After operation 2 | [4, 8]  |
| After operation 3 | [16, 8] |

Example 2

Input: nums = [2,1,3,5,6], k = 5, multiplier = 2

Output: [8,4,6,5,6]

| Operation         | Array           |
| ----------------- | --------------- |
| After operation 1 | [2, 2, 3, 5, 6] |
| After operation 2 | [4, 2, 3, 5, 6] |
| After operation 3 | [4, 4, 3, 5, 6] |
| After operation 4 | [4, 4, 6, 5, 6] |
| After operation 5 | [8, 4, 6, 5, 6] |

Constraints

Solution

// Brute Force
class Solution {
public:
    vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {
        for (int i = 0; i < k; i++) {
            int minIndex = 0;
            for (int j = 1; j < nums.size(); j++) {
                if (nums[j] < nums[minIndex]) {
                    minIndex = j;
                }
            }
            nums[minIndex] *= multiplier;
        }
        return nums;
    }
};

// Min Heap

class Solution {
public:
    vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {
        int n = nums.size();
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

        for (int i = 0; i < n; ++i) {
            pq.push({nums[i], i});
        }

        while (k > 0) {
            auto [val, idx] = pq.top();
            pq.pop();
            val = (val * multiplier);
            pq.push({val, idx});
            k--;
        }
        vector<int> result(n);
        while (!pq.empty()) {
            auto [val, idx] = pq.top();
            pq.pop();
            result[idx] = val;
        }

        return result;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Brute O(kn) O(1)
Min Heap O(nlogn) O(n)

Explanation

1. Intuition

2. Implementation

There is a follow up question for this problem, Problem 3266 .