Leetcode Best Time to Buy and Sell Stock II OJ 刷题 算法
来源:互联网 发布:linux shell执行exe 编辑:程序博客网 时间:2024/06/10 01:54
Best Time to Buy and Sell Stock II
ay 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).
思考
按理好像是要动态规划做
投机取巧, 直接把 上升段的值相加
直接比较相邻 2 个数的值, 就可以了
因为如果有连续跨越几个数的上升段, 也包含了相邻 2 个数的上升段
Solution
public class BestTimeBuySellStock { public static void main(String[] args) { System.out.println(maxProfit(new int[] { 1, 3, 4, 0, 1, 3, 2 })); System.out.println(maxProfit(new int[] { 3, 3,1,5,10,3, 4, 0, 1, 3, 2 })); } public static int maxProfit(int[] prices) { int result = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) { result += prices[i] - prices[i - 1]; } } return result; }}
其他解法
public static int maxProfit(int[] prices) { int result = 0; if (prices.length == 0) { return 0; } int startPrice = prices[0]; int endPrice = prices[0]; for (int i = 1; i < prices.length; i++) { while (i < prices.length && startPrice < prices[i]) { if (prices[i] < endPrice) { break; } else { endPrice = prices[i]; } i++; } result += endPrice - startPrice; if (i < prices.length) { startPrice = prices[i]; endPrice = prices[i]; } } return result; }
这个方法找出 连续上升段的起始值和终点值
将所有上升段的差值 累记 就得到了最大利润
0 0
- Leetcode Best Time to Buy and Sell Stock II OJ 刷题 算法
- LeetCode OJ:Best Time to Buy and Sell Stock II
- LeetCode OJ - Best Time to Buy and Sell Stock II
- [LeetCode OJ]Best Time to Buy and Sell Stock II
- LeetCode OJ:Best Time to Buy and Sell Stock
- LeetCode OJ:Best Time to Buy and Sell Stock III
- LeetCode OJ - Best Time to Buy and Sell Stock
- LeetCode OJ - Best Time to Buy and Sell Stock III
- [LeetCode OJ]Best Time to Buy and Sell Stock
- LeetCode OJ 121 Best Time to Buy and Sell Stock
- [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
- OC关于NSString和NSMutableString方法的使用
- oc 关于属性声明
- Collection集合框架和List集合笔记
- 关于PHP fopen函数在windows系统上创建中文命名的文档时乱码的问题
- MFC自制菜单(既绘制菜单的外观)
- Leetcode Best Time to Buy and Sell Stock II OJ 刷题 算法
- Linux学习笔记----rpm包and rpm命令管理
- 简单密码破译
- H--(LightOJ -- 1008
- 安卓学习笔记(一)自定义控件1
- C++ Primer : 第九章 : vector变长、string的其他操作以及容器适配器
- 10.1-5 双端队列deque
- Zookeeper监控的作用
- ActiveMQ(2) 安装