[LeetCode]Best Time to Buy and Sell Stock II
来源:互联网 发布:温和祛痘洗面奶知乎 编辑:程序博客网 时间:2024/06/16 11:05
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 {int sum = 0; public int maxProfit(int[] prices) { if(prices.length<1) return 0; maxProfit(prices,0); return sum; } private void maxProfit(int []prices,int start){ if(start>=prices.length-1) return; int buy = prices[start]; int buyIndex = start; for(int i=start+1;i<prices.length;i++){ if(prices[i]<=buy){ buy = prices[i]; buyIndex = i; }else{ break; } } int sell = prices[buyIndex]; int sellIndex = buyIndex; for(int i=buyIndex+1;i<prices.length;i++){ if(prices[i]>=sell){ sell = prices[i]; sellIndex = i; }else{ break; } } sum += sell-buy; maxProfit(prices,sellIndex+1); }}
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
- 求取圆内整数点(格点)的算法
- Android Animation 基础介绍 和例子
- Maven基础——实战篇
- ArrayList对对象中某属性排序
- SAP LSMW(摘自官网)
- [LeetCode]Best Time to Buy and Sell Stock II
- 9.1 改进以数据为中心的应用程序
- MOTO巨屏旗舰曝光 5.9英寸屏+4GB大内存
- ios简单画图显示
- 内存中堆区和栈区的区别
- 加入一家创业公司之前要考虑什么?
- 如何在Windows的cmd下让程序在后台执行?
- 设置请求超时的时间
- atoi itoa 为了自己以后查找方便