-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
19 additions
and
0 deletions.
There are no files selected for viewing
19 changes: 19 additions & 0 deletions
19
interview_prep/algorithm/java/ide_handicapped/best-time-to-buy-and-sell-stock/Solution.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |