3133. Minimum Array End
MediumView on LeetCode
Time: O(log n + log x)
Space: O(1)
Advertisement
Intuition
Minimum sum of array after operations: replace elements to minimize sum maintaining divisibility constraint.
Algorithm
- 1For each element starting from end: if nums[i] > nums[i-1]: set nums[i-1] = ceil(nums[i-1]/nums[i])*nums[i] to minimize while maintaining constraint.
Common Pitfalls
- •Work backwards. Each element must divide the previous. Minimize by rounding up to nearest multiple.
3133.cs
C#
// Approach: Spread n-1 bits into the free bit positions of x to form the smallest valid sequence.
// Time: O(log n + log x) Space: O(1)
public class Solution
{
public long MinEnd(int n, int x)
{
// Set x's 0s with (n - 1)'s LSb-to-MSb bits, preserving x's 1s. This
// operation increases x for (n - 1) iterations while preserving x's 1s.
int kMaxBit = (int)(Math.Log2(n) + Math.Log2(x) + 2);
long k = n - 1;
long ans = x;
int kBinaryIndex = 0;
for (int i = 0; i < kMaxBit; ++i)
{
if ((ans >> i & 1) == 0)
{
// Set x's 0 with k's bit if the running bit of k is 1.
if ((k >> kBinaryIndex & 1) == 1)
ans |= 1L << i;
++kBinaryIndex;
}
}
return ans;
}
}Advertisement
Was this solution helpful?