[LeetCode]Best Time to Buy and Sell Stock II
来源:互联网 发布:t315hw04 vb 编辑:程序博客网 时间:2024/05/18 03:19
Question
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).
本题难度Medium。
贪心法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
本题允许多次买卖,但是你手中最多只有1个股票(允许当天卖了当天再买入,第二天再卖)。因此只要尽最大可能低买高卖,只要明天比今天价格高,就应该今天买入明天再卖出。
【代码】
public class Solution { public int maxProfit(int[] prices) { //require int ans=0; for(int i=0;i<prices.length-1;i++){ if(prices[i]<prices[i+1]) ans+=prices[i+1]-prices[i]; } //ensure return ans; }}
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
- 信号量与互斥量
- 华东交通大学2016年ACM“双基”程序设计竞赛
- 4238: Save the Princess 博弈
- scanf返回值问题
- LeetCode 119: Pascal's Triangle II
- [LeetCode]Best Time to Buy and Sell Stock II
- 198. House Robber
- 二维数组问题
- 分析JAVA应用CPU占用过高的问题
- SpringAOP的概念(面向切面)
- 递归函数详解
- struts2中自定义转换
- MySql按周,按月,按日分组统计数据
- 赛门铁克23亿美元打造全球最大数字安全平台