zoukankan      html  css  js  c++  java
  • 【leetcode刷题笔记】Best Time to Buy and Sell Stock II

    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).

    解题:简单贪心,如果今天买,明天涨就不卖,如果明天跌就卖掉,如果后天涨明天就又买进来。

    代码:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         int answer = 0;
     5         if(prices.size() == 0)
     6             return 0;
     7         for(int i = 0;i < prices.size()-1;i++)
     8         {
     9             if(prices[i+1]>prices[i])
    10                 answer += prices[i+1]-prices[i];
    11         }
    12         return answer;
    13     }
    14 };

    我还问了这个问题:http://oj.leetcode.com/discuss/4082/why-do-i-have-to-add-if-prices-size-0-return-0

    Java版本:

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         int sum = 0;
     4         for(int i = 0;i < prices.length-1;i++){
     5             if(prices[i+1] > prices[i])
     6                 sum += prices[i+1]-prices[i];
     7         }
     8         return sum;
     9     }
    10 }
  • 相关阅读:
    yii之behaviors
    查看windows系统信息
    idm chrome扩展被阻止解决办法
    音乐乐理基础
    bootstrap4
    七牛上传整合CI
    提升上传速度
    卡漫绘图
    指针的操作
    定语从句八个易混淆
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3638719.html
Copyright © 2011-2022 走看看