exercism/zig/knapsack/knapsack.zig

31 lines
768 B
Zig
Raw Permalink Normal View History

2024-09-27 12:49:29 -04:00
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];
}