Simulation(TLE)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { private static final int MOD = 1000000007;
public int minimumPossibleSum(int n, int target) {
long sum = ((long) n) * (n + 1) / 2; sum %= MOD; int supplement = n + 1; for (int num = Math.min(n, target - 1); num > 0; num--) { int another = target - num; if (another > 0 && another < num) { sum -= num; another = target - supplement; while (another > 0 && another < num) { supplement++; another = target - supplement; } sum += supplement; sum %= MOD; supplement++; } else if (another >= num) { break; } }
return (int) sum; } }
|
Math
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { private static final int MOD = 1000000007;
public int minimumPossibleSum(int n, int target) { int m = target / 2;
if (n <= m) { return (int) (((long) n) * (n + 1) / 2 % MOD); } else { long sum = (((long) m) * (m + 1) / 2 % MOD); sum += ((((long) target) + target + n - m - 1) * (n - m) / 2 % MOD); return (int) (sum % MOD); } } }
|
References
2834. Find the Minimum Possible Sum of a Beautiful Array