Недавно я искал решения проблемы, которую нашел на LeetCode. Проблему можно увидеть здесь: https://leetcode.com/articles/best-time-to-buy-and-sell-stock-ii/#
Что касается подхода грубой силы к деталям статьи, я не понимаю, почему временная сложность равна O (n ^ n). Я считаю, что это должно быть O (n!). Я также не понимаю, почему пространственная сложность равна O (N), поскольку массивы, похоже, не хранятся.
Вот код грубой силы для решения проблемы:
class Solution {
public int maxProfit(int[] prices) {
return calculate(prices, 0);
}
public int calculate(int prices[], int s) {
if (s >= prices.length)
return 0;
int max = 0;
for (int start = s; start < prices.length; start++) {
int maxprofit = 0;
for (int i = start + 1; i < prices.length; i++) {
if (prices[start] < prices[i]) {
int profit = calculate(prices, i + 1) + prices[i] - prices[start];
if (profit > maxprofit)
maxprofit = profit;
}
}
if (maxprofit > max)
max = maxprofit;
}
return max;
}
}