Skip to content

2834. Find the Minimum Possible Sum of a Beautiful Array 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  // Same as 2829. Determine the Minimum Sum of a k-avoiding Array
  int minimumPossibleSum(int n, int target) {
    // These are the unique pairs that sum up to target (k):
    // (1, k - 1), (2, k - 2), ..., (ceil(k / 2), floor(k / 2)).
    // Our optimal strategy is to select 1, 2, ..., floor(k / 2), and then
    // choose k, k + 1, ... if necessary, as selecting any number in the range
    // [ceil(k / 2), k - 1] will result in a pair summing up to k.
    const int mid = target / 2;
    if (n <= mid)
      return trapezoid(1, n);
    return (trapezoid(1, mid) + trapezoid(target, target + (n - mid - 1))) %
           kMod;
  }

 private:
  static constexpr int kMod = 1'000'000'007;

  // Returns sum(a..b).
  long trapezoid(long a, long b) {
    return (a + b) * (b - a + 1) / 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  // Same as 2829. Determine the Minimum Sum of a k-avoiding Array
  public int minimumPossibleSum(int n, int target) {
    // These are the unique pairs that sum up to target (k):
    // (1, k - 1), (2, k - 2), ..., (ceil(k / 2), floor(k / 2)).
    // Our optimal strategy is to select 1, 2, ..., floor(k / 2), and then
    // choose k, k + 1, ... if necessary, as selecting any number in the range
    // [ceil(k / 2), k - 1] will result in a pair summing up to k.
    final int mid = target / 2; // floor(k / 2)
    if (n <= mid)
      return (int) trapezoid(1, n);
    return (int) ((trapezoid(1, mid) + trapezoid(target, target + (n - mid - 1))) % kMod);
  }

  private static final int kMod = 1_000_000_007;

  // Returns sum(a..b).
  private long trapezoid(long a, long b) {
    return (a + b) * (b - a + 1) / 2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  # Same as 2829. Determine the Minimum Sum of a k-avoiding Array
  def minimumPossibleSum(self, n: int, target: int) -> int:
    # These are the unique pairs that sum up to k (target):
    # (1, k - 1), (2, k - 2), ..., (ceil(k // 2), floor(k // 2)).
    # Our optimal strategy is to select 1, 2, ..., floor(k // 2), and then
    # choose k, k + 1, ... if necessary, as selecting any number in the range
    # [ceil(k // 2), k - 1] will result in a pair summing up to k.
    kMod = 1_000_000_007

    def trapezoid(a: int, b: int) -> int:
      """Returns sum(a..b)."""
      return (a + b) * (b - a + 1) // 2

    mid = target // 2  # floor(k // 2)
    if n <= mid:
      return trapezoid(1, n)
    return (trapezoid(1, mid) + trapezoid(target, target + (n - mid - 1))) % kMod