LeetCode in Kotlin

2834. Find the Minimum Possible Sum of a Beautiful Array

Medium

You are given positive integers n and target.

An array nums is beautiful if it meets the following conditions:

Return the minimum possible sum that a beautiful array could have modulo 109 + 7.

Example 1:

Input: n = 2, target = 3

Output: 4

Explanation: We can see that nums = [1,3] is beautiful.

It can be proven that 4 is the minimum possible sum that a beautiful array could have.

Example 2:

Input: n = 3, target = 3

Output: 8

Explanation: We can see that nums = [1,3,4] is beautiful.

It can be proven that 8 is the minimum possible sum that a beautiful array could have.

Example 3:

Input: n = 1, target = 1

Output: 1

Explanation: We can see, that nums = [1] is beautiful.

Constraints:

Solution

class Solution {
    fun minimumPossibleSum(n: Int, target: Int): Int {
        val mod = 1e9.toLong() + 7
        if (target > (n + n - 1)) {
            return (n.toLong() * (n + 1) % mod / 2).toInt()
        }
        val toChange = n - (target / 2).toLong()
        val sum = ((n * (n.toLong() + 1)) / 2) % mod
        val remain = target.toLong() - ((target / 2) + 1)
        return ((sum + (toChange * remain) % mod) % mod).toInt()
    }
}