hello-algo/codes/swift/chapter_greedy/max_capacity.swift
nuomi1 8d5e84f70a
Feature/chapter greedy swift (#720)
* feat: add Swift codes for greedy_algorithm article

* feat: add Swift codes for fractional_knapsack_problem article

* feat: add Swift codes for max_capacity_problem article

* feat: add Swift codes for max_product_cutting_problem article
2023-09-03 19:09:45 +08:00

38 lines
824 B
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: max_capacity.swift
* Created Time: 2023-09-03
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
func maxCapacity(ht: [Int]) -> Int {
// i, j
var i = 0, j = ht.count - 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)")
}
}