50.Best Time to Buy and Sell Stock II(贪心算法)
来源:互联网 发布:c语言和指针下载 编辑:程序博客网 时间:2024/06/17 08:20
题目原文:
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 int maxProfit(int[] prices) {int sum=0;//待返回的利益int len = prices.length;for(int i =1;i<len;i++){/*第i天的价格大于第i-1天的价格的时候,则第i-1天买,第i天卖*/if(prices[i-1]<prices[i]){sum += prices[i]-prices[i-1];}}return sum; }
0 0
- 50.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---贪心
- [C++]LeetCode: 77 Best Time to Buy and Sell Stock II (贪心算法)
- Best Time to Buy and Sell Stock II(JAVA)--贪心算法
- leetcode 122. Best Time to Buy and Sell Stock II-股票交易|贪心算法
- 122.leetcode Best Time to Buy and Sell Stock II(medium)[贪心算法 数组]
- 122. Best Time to Buy and Sell Stock II 类别:贪心算法 难度:medium
- Leetcode 贪心 Best Time to Buy and Sell Stock
- Leetcode 贪心 Best Time to Buy and Sell Stock III
- LeetCode 121 Best Time to Buy and Sell Stock (贪心)
- 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
- Best Time to Buy and Sell Stock II
- LeetCode Trapping Rain Water
- 应用层—万维网WWW
- 昨日股市暴跌熔断 赵薇亏3.3亿赔惨了(如何预测今年股市走向)
- phonegap(cordova) 自定义插件代码篇(三)----支付宝支付工具整合
- 深度学习总结
- 50.Best Time to Buy and Sell Stock II(贪心算法)
- jquery的.on()支持的事件
- 轻松学习之 IMP指针的作用
- ThinkPHP & jQuery.ajax 登录功能,无法重定向,自动刷新
- android上px与dp相互转换代码
- C# 原样复制excel工作表
- PDF的生成与下载
- 十道海量数据处理面试题与十个方法大总结
- 页面传递多条参数到后台