LeetCode-in-Java

3927. Minimize Array Sum Using Divisible Replacements

Medium

You are given an integer array nums.

You can perform the following operation any number of times:

Return the minimum possible sum of the array after performing any number of operations.

Example 1:

Input: nums = [3,6,2]

Output: 7

Explanation:

Example 2:

Input: nums = [4,2,8,3]

Output: 9

Explanation:

Example 3:

Input: nums = [7,5,9]

Output: 21

Explanation:

Constraints:

Solution

public class Solution {
    public long minArraySum(int[] nums) {
        int max = 0;
        long sum = 0;
        for (int num : nums) {
            if (num == 1) {
                return nums.length;
            }
            if (num > max) {
                max = num;
            }
        }
        int[] min = new int[max + 1];
        for (int num : nums) {
            min[num] = num;
        }
        for (int num : nums) {
            if (min[num] < num) {
                continue;
            }
            for (int i = num; i <= max; i += num) {
                if (num < min[i]) {
                    min[i] = num;
                }
            }
        }
        for (int num : nums) {
            sum += min[num];
        }
        return sum;
    }
}