- [数组]122. Best Time to Buy and Se
- Leetcode PHP题解--D109 122. Best T
- leetcode:122. Best Time to Buy a
- Leetcode122-Best Time to Buy and
- 跟我一起刷leetCode算法题9之Best Time to B
- [数组]121. Best Time to Buy and Se
- 121. Best Time to Buy and Sell S
- 【2019-07-30】leetcode(121-130)
- LeetCode Best Time to Buy and Se
- Leetcode 122. Best Time to Buy a
题目:122. Best Time to Buy and Sell Stock ||
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).
给一数组,表示一个商品每天的价钱。每天可以选择买入或者卖出该商品,求最大的收益。
思路:只要第二天比前一天的价格高,那必然可以将差价算入收益。累加即可。
class Solution {
public int maxProfit(int[] prices) {
int days = prices.length;
if(days == 0) return 0;
int profit = 0;
for(int i =1; i<days;i++){
if((prices[i] - prices[i-1]) > 0) profit += (prices[i]-prices[i-1]);
}
if(profit <= 0) profit = 0;
return profit;
}
}
网友评论