[LeetCode][Jave] Best Time to Buy and Sell Stock II
2015-05-19 20:50
309 查看
题目:
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).
题意:
给定一个数组,数组中的第i个元素值为给定的一只股票在第i天的价格。设计一个算法找到这只股票的最大收益。你可以任意次数的买卖这支股票。但是,在你买入这支股票之前,你必须先卖掉。
算法分析:
这个题特别容易想复杂,其实就是只要找到递增的区间差就行(注意:不可以在一天当中同时出现买和卖的行为)代码:
public class Solution { public int maxProfit(int[] prices) { int prf=0; if(prices==null||prices.length<=1) return 0; for(int i=1;i<prices.length;i++) { if(prices[i-1]<=prices[i]) { prf+=prices[i]-prices[i-1]; } } return prf; } }
相关文章推荐
- leetcode之Best Time to Buy and Sell Stock II
- 【LeetCode】Best Time to Buy and Sell Stock II &&Integer to Roman
- 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 I,II,III [leetcode]
- 【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 I&&II
- 【LeetCode】-Best Time to Buy and Sell Stock II
- 122.leetcode Best Time to Buy and Sell Stock II(medium)[贪心算法 数组]
- [LeetCode][JavaScript]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 I, 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