File tree Expand file tree Collapse file tree
src/kent/alg/leetcode/Array Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments