【LeetCode】 122. Best Time to Buy and Sell Stock II
2017-01-07 01:02
447 查看
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock
before you buy again).
public class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i - 1] < prices[i]) {
res += prices[i] - prices[i - 1];
}
}
return res;
}
}
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock
before you buy again).
public class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i - 1] < prices[i]) {
res += prices[i] - prices[i - 1];
}
}
return res;
}
}
相关文章推荐
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode: Permutations
- 【Leetcode】Container With Most Water
- 【LeetCode】Palindrome Number
- LeetCode Solutions : Sqrt(x)
- [Leetcode]Implement strStr()
- [LeetCode] Longest Consecutive Sequence
- [LeetCode] Restore IP Addresses 回溯
- LeetCode 5 Longest Palindromic Substring(C,C++,Python,Java)
- Factorial Trailing Zeroes -- leetcode
- LeetCode(147) Insertion Sort List
- Leetcode Shortest Word Distance II
- [LeetCode Solution 1] 236.Lowest Common Ancestor of a Binary Tree
- [LeetCode] Search Insert Position 解题报告
- [LeetCode] Spiral Matrix II
- 每天一道算法题(七)Leetcode – Word BreakII (Java)
- leetcode count pirmes
- leetcode题解日练--2016.8.6
- Java-LeetCode-3Sum
- LeetCode Index For Reference