RosettaCodeData/Task/Longest-increasing-subsequence/Julia/longest-increasing-subsequence.jl

21 lines
652 B
Julia
Raw Permalink Normal View History

2026-02-01 16:33:20 -08:00
function lis(arr::Vector{T}) where T
isempty(arr) && return copy(arr)
allsequences = Vector{Vector{T}}(undef, length(arr))
allsequences[begin] = [arr[begin]]
2023-07-01 11:58:00 -04:00
2026-02-01 16:33:20 -08:00
for i in firstindex(arr)+1:lastindex(arr)
nextseq = T[]
for j in firstindex(arr):i
if arr[j] < arr[i] && length(allsequences[j]) length(nextseq)
nextseq = allsequences[j]
2023-07-01 11:58:00 -04:00
end
end
2026-02-01 16:33:20 -08:00
allsequences[i] = push!(nextseq, arr[i])
2023-07-01 11:58:00 -04:00
end
2026-02-01 16:33:20 -08:00
_, idx = findmax(length, allsequences)
return allsequences[idx]
2023-07-01 11:58:00 -04:00
end
@show lis([3, 2, 6, 4, 5, 1])
@show lis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])