mirror of
https://codeberg.org/andyscott/exercism.git
synced 2024-12-22 14:43:10 -05:00
31 lines
768 B
Zig
31 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];
|
||
|
}
|