exercism/zig/knapsack/knapsack.zig

30 lines
768 B
Zig

const std = @import("std");
const mem = std.mem;
pub const Item = struct {
weight: usize,
value: usize,
pub fn init(weight: usize, value: usize) Item {
return Item{ .weight = weight, .value = value };
}
};
pub fn maximumValue(allocator: mem.Allocator, maximumWeight: usize, items: []const Item) !usize {
if (items.len == 0) return 0;
var dp: []usize = try allocator.alloc(usize, maximumWeight + 1);
defer allocator.free(dp);
@memset(dp, 0);
for (items) |item| {
var maxW = maximumWeight;
while (maxW > 0) : (maxW -= 1) {
if (item.weight <= maxW) {
dp[maxW] = @max(dp[maxW], dp[maxW - item.weight] + item.value);
}
}
}
return dp[maximumWeight];
}