|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=122 lang=java |
| 3 | + * |
| 4 | + * [122] Best Time to Buy and Sell Stock II |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (50.92%) |
| 10 | + * Total Accepted: 311.1K |
| 11 | + * Total Submissions: 604.3K |
| 12 | + * Testcase Example: '[7,1,5,3,6,4]' |
| 13 | + * |
| 14 | + * Say you have an array for which the i^th element is the price of a given |
| 15 | + * stock on day i. |
| 16 | + * |
| 17 | + * Design an algorithm to find the maximum profit. You may complete as many |
| 18 | + * transactions as you like (i.e., buy one and sell one share of the stock |
| 19 | + * multiple times). |
| 20 | + * |
| 21 | + * Note: You may not engage in multiple transactions at the same time (i.e., |
| 22 | + * you must sell the stock before you buy again). |
| 23 | + * |
| 24 | + * Example 1: |
| 25 | + * |
| 26 | + * |
| 27 | + * Input: [7,1,5,3,6,4] |
| 28 | + * Output: 7 |
| 29 | + * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit |
| 30 | + * = 5-1 = 4. |
| 31 | + * Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = |
| 32 | + * 3. |
| 33 | + * |
| 34 | + * |
| 35 | + * Example 2: |
| 36 | + * |
| 37 | + * |
| 38 | + * Input: [1,2,3,4,5] |
| 39 | + * Output: 4 |
| 40 | + * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit |
| 41 | + * = 5-1 = 4. |
| 42 | + * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you |
| 43 | + * are |
| 44 | + * engaging multiple transactions at the same time. You must sell before buying |
| 45 | + * again. |
| 46 | + * |
| 47 | + * |
| 48 | + * Example 3: |
| 49 | + * |
| 50 | + * |
| 51 | + * Input: [7,6,4,3,1] |
| 52 | + * Output: 0 |
| 53 | + * Explanation: In this case, no transaction is done, i.e. max profit = 0. |
| 54 | + * |
| 55 | + */ |
| 56 | +class Solution { |
| 57 | + public int maxProfit(int[] prices) { |
| 58 | + int profit = 0; |
| 59 | + int len = prices.length; |
| 60 | + for (int i = 1; i < len; i++) { |
| 61 | + if (prices[i] > prices[i-1]) { |
| 62 | + profit += prices[i] - prices[i-1]; |
| 63 | + } |
| 64 | + } |
| 65 | + return profit; |
| 66 | + } |
| 67 | +} |
| 68 | + |
0 commit comments