Example 1
Input
2
[{"customer":"An","total":100,"status":"paid"},{"customer":"Binh","total":300,"status":"paid"},{"customer":"An","total":250,"status":"paid"},{"customer":"Chi","total":900,"status":"cancelled"}]Expected output
An: 350 Binh: 300
Example 2
Input
5
[{"customer":"Dung","total":50,"status":"paid"},{"customer":"Chi","total":50,"status":"paid"},{"customer":"An","total":10,"status":"pending"}]Expected output
Chi: 50 Dung: 50
3 hidden tests · Limit 2 s · 256 MB
Viết hàm topCustomers(orders, k) nhận mảng đơn hàng dạng { customer, total, status } và số nguyên k, trả về mảng tối đa k phần tử dạng { customer, revenue }:
status === "paid".revenue là tổng total các đơn đã thanh toán của khách đó.revenue giảm dần; nếu bằng nhau thì theo tên khách tăng dần (so sánh chuỗi bằng <).orders đầu vào.Ví dụ
topCustomers([
{ customer: "An", total: 100, status: "paid" },
{ customer: "Binh", total: 300, status: "paid" },
{ customer: "An", total: 250, status: "paid" },
{ customer: "Chi", total: 900, status: "cancelled" },
], 2);
// [{ customer: "An", revenue: 350 }, { customer: "Binh", revenue: 300 }]TIP
Thử kết hợp filter, Object.groupBy, reduce và toSorted.
function topCustomers(orders, k) {
// trả về mảng [{ customer, revenue }]
}
Comments