LeetCode:Best Time to Buy and Sell Stock II
来源:互联网 发布:淘宝买笔记本主板 编辑:程序博客网 时间:2024/05/18 01:43
Best Time to Buy and Sell Stock II
Total Accepted: 49789 Total Submissions: 130095My SubmissionsSay 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).
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; }
0 0
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- [Leetcode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- LeetCode-Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock II
- malloc函数详解
- 黑马程序员-C基础-推箱子(入门级)笔记总结
- EGORefreshTableHeaderView与LoadMoreTableFooterView的使用
- 剑指offer-第三章-高质量的代码
- 字符串
- LeetCode:Best Time to Buy and Sell Stock II
- Xcode 6.2 error::can only be used when targeting iOS 4.2 or later错误处理
- 轻松搞定面试中的二叉树题目
- 3-46
- Ember.js学习总结
- 格式化为两位小数
- piwik学习1(index.php)
- Linux下socket编程
- 素数,以此做为我23岁的生日特别篇(读书笔记——什么是数学)