Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fcc1c4a

Browse files
committed
Stock prices I done
1 parent 39ec46f commit fcc1c4a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.leetcode.arrays;
2+
3+
/**
4+
* Problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
5+
*
6+
* @author rampatra
7+
* @since 2019年04月23日
8+
*/
9+
public class BuySellStocks {
10+
11+
/**
12+
* Time complexity: O(n)
13+
* where,
14+
* n = no. of stock prices
15+
* <p>
16+
* Runtime: <a href="https://leetcode.com/submissions/detail/224463627/">0 ms</a>.
17+
*
18+
* @param prices
19+
* @return
20+
*/
21+
public static int maxProfit(int[] prices) {
22+
int profit = 0;
23+
int buyPrice = Integer.MAX_VALUE;
24+
25+
for (int i = 0; i < prices.length; i++) {
26+
if (prices[i] < buyPrice) {
27+
buyPrice = prices[i];
28+
} else if (prices[i] - buyPrice > profit) {
29+
profit = prices[i] - buyPrice;
30+
}
31+
}
32+
33+
return profit;
34+
}
35+
36+
public static void main(String[] args) {
37+
38+
System.out.println(maxProfit(new int[]{7, 1, 5, 3, 6, 4}));
39+
System.out.println(maxProfit(new int[]{7, 1, 5, 0, 6, 4}));
40+
System.out.println(maxProfit(new int[]{4, 3, 2, 1}));
41+
42+
// edge cases
43+
System.out.println(maxProfit(new int[]{}));
44+
System.out.println(maxProfit(new int[]{1}));
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /