Skip to content

Commit ad11ff1

Browse files
committed
BestTimeToBuyAndSellStockII
1 parent 39753c0 commit ad11ff1

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package kent.alg.leetcode.Array;
2+
/**
3+
Say you have an array for which the ith element is the price of a given stock on day i.
4+
5+
Design an algorithm to find the maximum profit.
6+
You may complete as many transactions as you like
7+
(ie, buy one and sell one share of the stock multiple times).
8+
However, you may not engage in multiple transactions at the same time
9+
(ie, you must sell the stock before you buy again).
10+
*/
11+
public class BestTimeToBuyAndSellStockII {
12+
13+
// Time complexity : O(n). Only a single pass is needed.
14+
public int maxProfit(int[] prices) {
15+
16+
int maxProfit = 0;
17+
18+
for(int i=0; i<prices[i]; i++) {
19+
if(prices[i]> prices[i-1])
20+
maxProfit = prices[i] - prices[i-1];
21+
}
22+
return maxProfit;
23+
}
24+
25+
public static void main(String[] args) {
26+
// TODO Auto-generated method stub
27+
28+
}
29+
30+
}

0 commit comments

Comments
 (0)