33 lines
782 B
Java
33 lines
782 B
Java
|
package com.zerroi.leetcode.ThreeFour;
|
||
|
|
||
|
public class MaxProfit {
|
||
|
public static void main(String[] args) {
|
||
|
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class SolutionFirst {
|
||
|
// O(n^2) solution can't access
|
||
|
public int maxProfitFirst(int[] prices) {
|
||
|
int maxProfit = 0;
|
||
|
for (int i = 0; i < prices.length; i++) {
|
||
|
for (int j = i + 1; j < prices.length; j++) {
|
||
|
maxProfit = Math.max(maxProfit, prices[j] - prices[i]);
|
||
|
}
|
||
|
}
|
||
|
return maxProfit;
|
||
|
}
|
||
|
|
||
|
|
||
|
// O(n) solution
|
||
|
public int maxProfit(int[] prices) {
|
||
|
int cost = Integer.MAX_VALUE;
|
||
|
int profit = 0;
|
||
|
for (int price : prices) {
|
||
|
cost = Math.min(cost, price);
|
||
|
profit = Math.max(profit, price - cost);
|
||
|
}
|
||
|
return profit;
|
||
|
}
|
||
|
}
|