Find the Minimum Possible Sum of a Beautiful Array — LeetCode 2834 Python Solution
MediumGreedyMath
- Problem
- #2834
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given positive integers n and target. An array nums is beautiful if it meets the following conditions: nums.length == n.
Example
- Input
- n = 2, target = 3
- Output
- 4
- Explanation
- We can see that nums = [1,3] is beautiful.
Python solution
Python
class Solution:
def minimumPossibleSum(self, n: int, target: int) -> int:
mod = 10**9 + 7
m = target // 2
if n <= m:
return ((1 + n) * n // 2) % mod
return ((1 + m) * m // 2 + (target + target + n - m - 1) * (n - m) // 2) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(1) |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2834. Find the Minimum Possible Sum of a Beautiful Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2834. Find the Minimum Possible Sum of a Beautiful Array?
- LeetCode 2834. Find the Minimum Possible Sum of a Beautiful Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2834. Find the Minimum Possible Sum of a Beautiful Array?
- The Python solution on this page runs in O(1).
- What is the space complexity of LeetCode 2834. Find the Minimum Possible Sum of a Beautiful Array?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2834. Find the Minimum Possible Sum of a Beautiful Array cover?
- LeetCode 2834. Find the Minimum Possible Sum of a Beautiful Array is tagged Greedy and Math on LeetCode.