XAMPP案例 376浏览

# 题目描述:

Input：[7,1,5,3,6,4]
Output:5

``````int maxProfit(vector<int>& prices) {
int sell = 0, buy = INT_MIN;
for (int i = 0; i < prices.size(); ++i) {
sell = max(sell, buy + prices[i]);
}
return sell;
}``````

# 第二题

Input: [3,2,6,5,0,3], k = 2
Output:7

``````// 主函数

int maxProfit(int k, vector<int>& prices) {
int days = prices.size();
if (days < 2) {
return 0;
}
if (k >= days) {
return maxProfitUnlimited(prices);
}
vector<int> buy(k + 1, INT_MIN), sell(k + 1, 0);
for (int i = 0; i < days; ++i) {
for (int j = 1; j <= k; ++j) {
sell[j] = max(sell[j], buy[j] + prices[i]);
} }
return sell[k];
}
// 辅函数
int maxProfitUnlimited(vector<int> prices) {
int maxProfit = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] > prices[i-1]) {
maxProfit += prices[i] - prices[i-1];
} }
return maxProfit;
}
``````

### Swift 编程语言版本

``````func maxProfit(_ prices: [Int]) -> Int {
calculateProfit(prices, 0)
}

func calculateProfit(_ prices: [Int], _ index: Int) -> Int {
if index >= prices.count {return 0}
var max = 0
for i in 0..<prices.count {
var maxProfit = 0
for j in i+1..<prices.count {
if prices[i] < prices[j] {
let curProfit = prices[j] - prices[i] + calculateProfit(prices, i + 1)
if curProfit > maxProfit {
maxProfit = curProfit
}
}
}
if maxProfit > max {
max = maxProfit
}
}
return max
}
``````
end