1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 ソートメニュー応用編 JavaScript 部分列

Last updated at Posted at 2022-09-13

部分列 (paizaランク B 相当)

大きい方から足して,和が初めてx以上になった時の要素数が答えです。
事前準備として数列aを大きい順(降順)にソートしておきます。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");
//数列の長さを表す整数 n, x
const [n, x] = lines[0].split(" ").map(Number);
//数列 a
const a = lines[1].split(" ").map(Number);

//数列aを降順にソートする
a.sort((a, b) => b - a);

//大きい方から足して,和が初めてx以上になった時の要素数が答え
let sum = 0;//和
let ans = -1;//答えの要素数。和sumを x 以上にできない場合は、代わりに -1 
for (let i = 0; i < n; i++) {
    sum += a[i];
    if (sum >= x) {
        ans = i + 1;
        break;
    }
}
console.log(ans);
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?