mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-14 16:16:06 +00:00
772183705e
* Add Russian docs site baseline * Add Russian localized codebase * Polish Russian code wording * Update ru code translation. * Update code translation and chapter covers. * Fix pythontutor extraction. * Add README and landing page. * placeholder of profiles * Use figures of English version * Remove chapter paperbook
39 lines
1.2 KiB
Swift
39 lines
1.2 KiB
Swift
/**
|
|
* File: max_capacity.swift
|
|
* Created Time: 2023-09-03
|
|
* Author: nuomi1 (nuomi1@qq.com)
|
|
*/
|
|
|
|
/* Максимальная вместимость: жадный алгоритм */
|
|
func maxCapacity(ht: [Int]) -> Int {
|
|
// Инициализировать i и j так, чтобы они располагались по двум концам массива
|
|
var i = ht.startIndex, j = ht.endIndex - 1
|
|
// Начальная максимальная вместимость равна 0
|
|
var res = 0
|
|
// Выполнять жадный выбор в цикле, пока две доски не встретятся
|
|
while i < j {
|
|
// Обновить максимальную вместимость
|
|
let cap = min(ht[i], ht[j]) * (j - i)
|
|
res = max(res, cap)
|
|
// Сдвигать внутрь более короткую сторону
|
|
if ht[i] < ht[j] {
|
|
i += 1
|
|
} else {
|
|
j -= 1
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
@main
|
|
enum MaxCapacity {
|
|
/* Driver Code */
|
|
static func main() {
|
|
let ht = [3, 8, 5, 2, 7, 7, 3, 4]
|
|
|
|
// Жадный алгоритм
|
|
let res = maxCapacity(ht: ht)
|
|
print("Максимальная вместимость = \(res)")
|
|
}
|
|
}
|