Skip to content

Commit

Permalink
best-time-to-buy-and-sell-stock
Browse files Browse the repository at this point in the history
  • Loading branch information
s50600822 committed Nov 24, 2023
1 parent 5f9302c commit 24ecedc
Showing 1 changed file with 19 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution {
public static int maxProfit(int[] prices) {
int boughtIdx = 0;
int profit = 0;
for(int i=1; i< prices.length; i ++){
if(prices[i] > prices[boughtIdx]){
profit = Math.max(profit, prices[i] - prices[boughtIdx]);
}else{
boughtIdx = i;
}
}
return profit;
}
public static void main(String[] args) {
//https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
assert maxProfit(new int[]{7,1,5,3,6,4}) == 5;
assert maxProfit(new int[]{7,6,4,3,1}) == 0;
}
}

0 comments on commit 24ecedc

Please sign in to comment.