Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 40833a2

Browse files
Brute force approach
1 parent 497e463 commit 40833a2

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

src/main/java/com/leetcode/arrays/BuySellStocks.java

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -39,20 +39,19 @@ public class BuySellStocks {
3939
* @param prices
4040
* @return
4141
*/
42-
public static int maxProfit(int[] prices) {
43-
int profit = 0;
44-
int buyPrice = Integer.MAX_VALUE;
45-
46-
for (int i = 0; i < prices.length; i++) {
47-
if (prices[i] < buyPrice) {
48-
buyPrice = prices[i];
49-
} else if (prices[i] - buyPrice > profit) {
50-
profit = prices[i] - buyPrice;
42+
public class Solution {
43+
public int maxProfit(int prices[]) {
44+
int maxprofit = 0;
45+
for (int i = 0; i < prices.length - 1; i++) {
46+
for (int j = i + 1; j < prices.length; j++) {
47+
int profit = prices[j] - prices[i];
48+
if (profit > maxprofit)
49+
maxprofit = profit;
5150
}
5251
}
53-
54-
return profit;
52+
return maxprofit;
5553
}
54+
}
5655

5756
public static void main(String[] args) {
5857

0 commit comments

Comments
 (0)