LeetCode:Best Time to Buy and Sell Stock II
2015-06-24 20:31
405 查看
Best Time to Buy and Sell Stock II
Total Accepted: 49789 TotalSubmissions: 130095My Submissions
Question
Solution
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).
Hide Tags
Array Greedy
方法一:Greedy(贪心算法)【if(a[i]<a[i+1]){num+=a[i+1]-a[i]}】
public int maxProfit(int[] prices) { int num=0; for(int i=0;i<prices.length-1;i++){ if(prices[i]<prices[i+1]){ num+=(prices[i+1]-prices[i]); } } return num; }
方法二:动规思想
public int maxProfit(int[] prices) { int i=0,num=0; boolean buy=false; for(;i<prices.length-1;i++){ if(buy&&prices[i]>prices[i+1]){ num+=prices[i]; buy=false; } if(!buy&&prices[i]<prices[i+1]){ num-=prices[i]; buy=true; } } if(buy){ num+=prices[i]; } return num; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)