Brute Force
Intuition
The simplest approach is to consider every possible pair of buy and sell days. For each day, we look at all future days and calculate the profit. We keep track of the maximum profit seen across all pairs. While correct, this approach is too slow for large inputs due to the nested loops.
Algorithm
- Initialize maxProfit to 0.
- Use an outer loop to iterate over each possible buy day i from 0 to n-2.
- Use an inner loop to iterate over each possible sell day j from i+1 to n-1.
- Calculate profit = prices[j] - prices[i]. If profit > maxProfit, update maxProfit.
- Return maxProfit.
O(n^2)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxProfit = 0;
for (int i = 0; i < prices.size(); i++) {
for (int j = i + 1; j < prices.size(); j++) {
int profit = prices[j] - prices[i];
maxProfit = max(maxProfit, profit);
}
}
return maxProfit;
}
};class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
maxProfit = Math.max(maxProfit, profit);
}
}
return maxProfit;
}
}def maxProfit(prices: list[int]) -> int:
max_profit = 0
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
profit = prices[j] - prices[i]
max_profit = max(max_profit, profit)
return max_profitfunc maxProfit(prices []int) int {
maxP := 0
for i := 0; i < len(prices); i++ {
for j := i + 1; j < len(prices); j++ {
profit := prices[j] - prices[i]
if profit > maxP {
maxP = profit
}
}
}
return maxP
}