Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
LeetCode 121 - Best time to buy and sell stock - O(n) solution
//'main' method must be in a class 'Rextester'. //openjdk version '11.0.5' import java.util.*; import java.lang.*; //LeetCode 121 - Best time to Buy and Sell Stock //input [7,1,5,3,6,2] //output - 5 (max profit) class Rextester { public static void main(String args[]) { System.out.println("Max profit is: "); int[] stock = new int[]{7,1,5,3,6,2}; System.out.println(maxProfit(stock)); } public static int maxProfit(int[] prices) { int minValue=Integer.MAX_VALUE; int maxProfit=0; for(int price:prices){ if(price>minValue) maxProfit = Math.max(maxProfit,(price-minValue)); if(price<minValue) minValue = price; } return maxProfit; } }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
Java Q4
Day 2
1B
pow x^n
1.5
3a
Just numbers
Case 2nd Clear
Bubble Sort
Apple Banana Pear question
Please log in to post a comment.