Skip to content

Latest commit

 

History

History
40 lines (34 loc) · 810 Bytes

2178.拆分成最多数目的正偶数之和.md

File metadata and controls

40 lines (34 loc) · 810 Bytes

2178.拆分成最多数目的正偶数之和

/*
 * @lc app=leetcode.cn id=2178 lang=typescript
 *
 * [2178] 拆分成最多数目的正偶数之和
 */

// @lc code=start
function maximumEvenSplit(n: number): number[] {}
// @lc code=end

解法 1: 贪心

function maximumEvenSplit(n: number): number[] {
  if (n & 1) return []
  const res: number[] = []
  for (let i = 2; i <= n; i += 2) {
    res.push(i)
    n -= i
  }
  if (n) res[res.length - 1] += n
  return res
}

Case

test.each([
  { input: { finalSum: 12 }, output: [2, 4, 6] },
  { input: { finalSum: 7 }, output: [] },
  { input: { finalSum: 28 }, output: [6, 8, 2, 12] },
])('input: finalSum = $input.finalSum', ({ input: { finalSum }, output }) => {
  expect(maximumEvenSplit(finalSum)).toEqual(output)
})