[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
原创粉丝点击